目录

js实现关键词搜索

目录

js实现关键词搜索

<!doctype html>
  
<html>
  
<head>
  
<meta charset="utf-8">
  
<meta name="author" content="http://www.softwhy.com/" />
  
<title>蚂蚁部落</title>
  
<style type="text/css">
  
* {
  
margin: 0;
  
padding: 0;
  
}
  
input {
  
display: block;
  
width: 600px;
  
height: 50px;
  
border: #EE491F 1px solid;
  
margin: 10px auto 0;
  
text-indent: 10px;
  
}
  
ul {
  
display: block;
  
width: 600px;
  
border: #CCC 1px solid;
  
margin: 0 auto;
  
}
  
li {
  
list-style: none;
  
display: block;
  
width: 100%;
  
}
  
a {
  
display: block;
  
width: 100%;
  
height: 40px;
  
border-bottom: #CCC 1px solid;
  
text-decoration: none;
  
color: #333;
  
line-height: 40px;
  
font-size: 12px;
  
}
  
</style>
  
<script>
  
window.onload = function() {
  
var data = {
  
"specialty": [{
  
"specialtyName": "div教程",
  
"href": "https://www.softwhy.com"
  
}, {
  
"specialtyName": "css教程",
  
"href": "http://www.softwhy.com"
  
}, {
  
"specialtyName": "div css教程",
  
"href": "http://www.softwhy.com"
  
}, {
  
"specialtyName": "css3教程",
  
"href": "http://www.softwhy.com"
  
}, {
  
"specialtyName": "jquery教程",
  
"href": "http://www.softwhy.com"
  
}]
  
}
  
  
var input = document.getElementsByTagName("input")[0];
  
var ul = document.getElementsByTagName("ul")[0];
  
ul.style.display = "none";
  
  
input.onkeyup = function() {
  
remove();
  
var arr_1 = [];
  
var arr_2 = [];
  
for (var index = 0; index < data.specialty.length; index++) {
  
if (data.specialty[index].specialtyName.indexOf(this.value) > -1 && this.value.length > 0) {
  
arr_1.push(data.specialty[index].specialtyName);
  
arr_2.push(data.specialty[index].href);
  
}
  
}
  
console.log(arr_1);
  
console.log(arr_2);
  
if (arr_1.length > 0) {
  
remove();
  
create(arr_1, arr_2);
  
}
  
}
  
  
function create(arr_1, arr_2) {
  
ul.style.display = "block";
  
for (var index = 0; index < arr_1.length; index++) {
  
var li = document.createElement("li");
  
li.innerHTML = "<a href='" + arr_2[index] + "'>" + arr_1[index] + "</a>";
  
ul.appendChild(li);
  
}
  
}
  
  
function remove() {
  
ul.style.display = "none";
  
for (var index = ul.childNodes.length - 1; index >= 0; index--) {
  
ul.removeChild(ul.childNodes[index]);
  
}
  
}
  
}
  
</script>
  
</head>
  
<body>
  
<input type="text" value="" placeholder="请输入搜索关键词" />
  
<ul></ul>
  
</body>
  

</html>

效果如图: https://i-blog.csdnimg.cn/blog_migrate/39405b81a941577db9395c18970a6412.png