简单的javascript过滤/搜索多个列表而不是一个?

时间:2017-09-20 18:55:15

标签: javascript search

我有一些简单的代码,允许过滤列表项,它几乎完美地工作。唯一的问题是搜索框只搜索第一个UL,如何进行搜索?

使用Javascript:

{{1}}

HTML:

{{1}}

2 个答案:

答案 0 :(得分:1)

首先使用唯一ID和同一个类

<ul id="myUL1" class="ul">
  <li><a href="#">bob</a></li>
  <li><a href="#">rob</a></li>

  <li><a href="#">tom</a></li>
  <li><a href="#">mark</a></li>
</ul>

<ul id="myUL2" class="ul">
  <li><a href="#">purse</a></li>
  <li><a href="#">cat</a></li>

  <li><a href="#">pencil</a></li>
  <li><a href="#">sharpner</a></li>
</ul>

然后修改脚本以定位所有LI,无论UL如何,只要它具有该类

function myFunction() {

  var input  = document.getElementById('myInput'),
      filter = input.value.toUpperCase(),
      li     = document.querySelectorAll(".ul li");

  // Loop through all list items, and hide those who don't match the search query
  for (var i = 0; i < li.length; i++) {
    var a = li[i].querySelector("a");

    if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}

答案 1 :(得分:0)

您可以使用document.querySelector选择两个列表的子项:

&#13;
&#13;
function myFunction() {
  var query = document.querySelector('#myInput').value;
  
  // this wil grab all <li> elements from all <ul> elements on the page
  // however, you will want to specify a unique attribute for only the elements you wish to include
  var elements = document.querySelectorAll('ul > li');
  
  for (var i = 0; i < elements.length; i ++) {
    var el = elements[i];
    if (el.innerText.indexOf(query) !== -1)
      el.style.display = '';
    else
      el.style.display = 'none';
  }
}
&#13;
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="search">
<ul id="myUL" class="ul1">
  <li><a href="#">bob</a></li>
  <li><a href="#">rob</a></li>

  <li><a href="#">tom</a></li>
  <li><a href="#">mark</a></li>
</ul>

<ul id="myUL2" class="ul2">
  <li><a href="#">purse</a></li>
  <li><a href="#">cat</a></li>

  <li><a href="#">pencil</a></li>
  <li><a href="#">sharpner</a></li>
</ul>
&#13;
&#13;
&#13;