Filter/Search 栏(<a> 元素列表)- 不工作

Filter/Search bar (list of <a> elements) - not working

我正在尝试使用 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>

首先,你有很多不必要的变数。您只需要两个,一个获取列表的值,另一个获取过滤器的值。如果有多个元素,则使用 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>