首页 > 解决方案 > 如何使用 Javascript 一次过滤和搜索多个 div?

问题描述

我有一个很长的项目列表,我希望用户能够轻松搜索这些项目。

我试图实施这个解决方案: https ://www.w3schools.com/howto/howto_js_filter_lists.asp 。

但是,由于我们的限制CMS,我需要将此列表拆分为多个 div。我目前有两个 id 为“ s-lg-254”和“ s-lg-255”的 div,每个 div 都包含一个ulid 为“ ul1”和“ ul2”的 div。

这是当前代码

    function journalsearch(ulID) {
   // Declare variables
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById('input1');
  filter = input.value.toUpperCase();
ul = document.getElementById(ulID);
  li = ul.getElementsByTagName('li');

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

HTML search box

<input type="text" id="input1" onkeyup="journalsearch('ul1', 'ul2')" placeholder="Search for journal titles...">

搜索框按预期过滤了两个列表中的第一个,但我尝试过的任何尝试都无法说服它同时过滤第二个。

我很新Javascript,所以会很感激任何帮助!

标签: javascripthtml

解决方案


一种解决方案是传递任意数量的 id,但在循环中将它们作为参数引用。

function journalsearch() {
   // Declare variables
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById('input1');
  filter = input.value.toUpperCase();
  
  for (var j=0; j < arguments.length; j++) {
  ulID = arguments[j];
ul = document.getElementById(ulID);
  li = ul.getElementsByTagName('li');

  // Loop through all list items, and hide those who don't match the search query
  for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
  li[i].style.display = "";
} else {
  li[i].style.display = "none";
}
  }
  }
}
<input type="text" id="input1" onkeyup="journalsearch('ul1', 'ul2')" placeholder="Search for journal titles...">
<ul id="ul2"></ul>
<ul id="ul1"></ul>


推荐阅读