js搜尋關鍵詞自動匹配功能程式碼例項

antzone發表於2017-04-17

分享一段程式碼例項,它實現了搜尋關鍵詞自動匹配的功能。

如果輸入的關鍵詞和詞庫中的指定內容匹配,那麼就會下拉顯示。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!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>

相關文章