JavaScript Live搜索容器

时间:2017-05-17 06:09:00

标签: javascript

我正在JS的某些方面进行实时搜索。我一直在尝试修改此https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_list

做我正在寻找的事情,我怎么似乎无法理解我做错了什么。非常感谢任何指针或更正。

  

JS它应该隐藏任何不包含搜索的twit

    var navbarSearchbutton = document.getElementById('navbar-search-button')[0];
navbarSearchbutton.addEventListener('onkeyup', function() {
  searchFunction();
});

function searchFunction() {
    var input, filter, ul, li, a, i, foo;
    foo = document.getElementsByClassName("twit");
    input = document.getElementById("navbar-search-input");
    filter = input.value.toUpperCase();
    li = document.getElementsByClassName("twit-text");
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("P")[0];
        if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            foo[i].style.display = "none";
        }
    }
}
  

搜索框的HTML和我正在搜索的内容。

          <li class="navitem navbar-search">
        <input type="text" id="navbar-search-input" placeholder="Search...">
        <button type="button" id="navbar-search-button"><i class="fa fa-search"></i></button>
      </li>
    </ul>
  </nav>
</header>

    <main class="twit-container">
  <article class="twit">
<div class="twit-icon">
  <i class="fa fa-bullhorn"></i>
</div>
<div class="twit-content">
  <p class="twit-text">
    A body in motion must remain in motion unless acted upon by an outside force.
  </p>
  <p class="twit-attribution">
    <a href="#">NewtonRulez</a>
  </p>
</div>

1 个答案:

答案 0 :(得分:0)

首先,你得到('id导航搜索按钮。所以,它不会返回一个id。 其次,按类名搜索的逻辑不起作用。以下是更新的搜索功能。我保持了你跟随的逻辑,按类名搜索项目。您需要将类名设置为任何新条目的twit-attribution。

function searchFunction() {
    var input, filter, ul, li, a, i, foo;
    foo = document.getElementsByClassName("twit");
    input = document.getElementById("navbar-search-input");
    filter = input.value.toUpperCase();
    li = document.getElementsByClassName("twit-attribution");
    for (i = 0; i < li.length; i++) {
        a = li[i];
        if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
            a.style.display = "";
        } else {
            a.style.display = "none";
        }
    }
}