js搜索关键词自动匹配功能代码实例

快乐打工仔 分类:实例代码

分享一段代码实例,它实现了搜索关键词自动匹配的功能。

如果输入的关键词和词库中的指定内容匹配,那么就会下拉显示。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<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.pipipi.net"
    }, {
      "specialtyName": "css教程",
      "href": "http://www.pipipi.net"
    }, {
      "specialtyName": "div css教程",
      "href": "http://www.pipipi.net"
    }, {
      "specialtyName": "css3教程",
      "href": "http://www.pipipi.net"
    }, {
      "specialtyName": "jquery教程",
      "href": "http://www.pipipi.net"
    }]
  }
 
  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>

js搜索关键词自动匹配功能代码实例,这样的场景在实际项目中还是用的比较多的,关于js搜索关键词自动匹配功能代码实例就介绍到这了。

js搜索关键词自动匹配功能代码实例属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容