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>

效果如图:

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值