通过JavaScript过滤ul列表未正确过滤列表

时间:2018-02-13 22:30:23

标签: javascript html

我正在尝试为ul实现过滤器列表,但我的JavaScript函数似乎没有接受输入并通过列表进行过滤。我不确定为什么会发生这种情况。我还尝试将for循环更改为for (i = 0; i < ul.length; i++),以搜索ul,但它似乎也没有响应。

HTML:

<input type="text" id="myMovies" onkeyup="searchTitle()" placeholder="Is your movie on here?">
        <ul id="movieList">
            <li>item 1</li>
            <li>item 2</li>
            <li>item 3</li>
            <li>item 4</li>
        </ul>

使用Javascript:

function searchTitle(){
    var input, filter,  ul, li, a, i;
    input = document.getElementById("myMovies");
    filter = input.nodeValue.toUpperCase();
    ul = document.getElementById("movieList");
    li = ul.getElementsByTagName("li");

    for (i = 0; i < li.length; i++){
        a = li[i].getElementsByTagName("a"[0]);
        if (a.innerHTML.toUpperCase().indexof(filter) > -1) {
            li[a].style.display = "";
        }
        else{
            li[a].style.display = "Not found";
        }
    }
}

2 个答案:

答案 0 :(得分:0)

也许这是你a = li[i].getElementsByTagName("a"[0]);行的错字,也许你想做a = li[i].getElementsByTagName("a")[0];

答案 1 :(得分:0)

这是一个完成你似乎正在尝试的样本。

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript">
      function searchTitle(){
    var input, filter,  ul, li, a, i;
      input = document.getElementById("myMovies");
      filter = input.value.toUpperCase();
      window.status = filter;
    ul = document.getElementById("movieList");
    li = ul.getElementsByTagName("li");

    for (i = 0; i < li.length; i++){
        a = li[i];
        if (a.textContent.toUpperCase().indexOf(filter) > -1) {
            a.style.display = "";
        }
        else{
            a.style.display = "none";
        }
    }
}
    </script>

  </head>
  <body>
<input type="text" id="myMovies" onkeyup="searchTitle()" placeholder="Is your movie on here?">
        <ul id="movieList">
            <li>item 1</li>
            <li>item 2</li>
            <li>item 3</li>
            <li>item 4</li>
        </ul>   
  </body>
</html>