过滤/搜索栏(<a> elements) - not working

时间:2017-06-10 00:55:21

标签: javascript html search searchbar

I am trying to use this example by w3schools列表以添加搜索栏。我无法让它工作,我已更改它以匹配我的元素但是没有成功。我必须将我的js与HTML文档分开,所以没有<script> 我的问题是它不起作用,我不知道如何调试它。 这是我的js文件:

//search bar
function myFunction() {
// Declare variables
var input, filter, ul, div, li, a, span, i;
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
ul = document.getElementById("container");
span = ul.getElementsByTagName('span');

// Loop through all list items, and hide those who don't match the search query
for (i = 0; i < li.length; i++) {
    a = span[i].getElementsByTagName("a")[0];
    if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
        span[i].style.display = "";
    } else {
        span[i].style.display = "none";
    }
  }
}
document.getElementById('myInput').addEventListener('keyup', myFunction);

我的HTML文件

<div class="container">
    <input type="text" id="myInput" placeholder="Search for names..">
    <div id="container">
        <span><a href="#" class="myButton" id="nico">Nico Nico Nii!!</a></span>
        <span><a href="#" class="myButton" id="redbone">Childish Gambino - Redbone</a></span>
        <span><a href="#" class="myButton" id="americaf">America F*ck Yeah!</a></span>
</div>
</div>

1 个答案:

答案 0 :(得分:2)

首先,你有很多不必要的变量。您只需要两个,一个用于获取列表的值,另一个用于获取过滤器的值。如果有多个元素,请改用class。请参阅以下工作代码:

//search bar
function myFunction() {
var input, filter;
input = document.getElementsByClassName('myLinks');
filter = document.getElementById('myInput').value.toUpperCase();
// Loop through all list items, and hide those who don't match the search query
for (i = 0; i < input.length; i++) {
    var currentElem = input[i];
    var currentElemChild = input[i].children[0]
    if (currentElemChild.innerHTML.toUpperCase().indexOf(filter) > -1) {
        currentElem.style.display = "";
    } else {
        currentElem.style.display = "none";
    }
  }
}
document.getElementById('myInput').addEventListener('keyup', myFunction);
<div>
    <input type="text" id="myInput" placeholder="Search for names..">
    <ul id="container">
        <li class="myLinks"><a href="#" id="nico">Nico Nico Nii!!</a></li>
        <li class="myLinks"><a href="#" id="redbone">Childish Gambino - Redbone</a></li>
        <li class="myLinks"><a href="#" id="americaf">America F*ck Yeah!</a></li>
</ul>
</div>