javascript - 如何使用 Javascript 一次过滤和搜索多个 div?
问题描述
我有一个很长的项目列表,我希望用户能够轻松搜索这些项目。
我试图实施这个解决方案: https ://www.w3schools.com/howto/howto_js_filter_lists.asp 。
但是,由于我们的限制CMS
,我需要将此列表拆分为多个 div。我目前有两个 id 为“ s-lg-254
”和“ s-lg-255
”的 div,每个 div 都包含一个ul
id 为“ 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
,所以会很感激任何帮助!
解决方案
一种解决方案是传递任意数量的 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>
推荐阅读
- html - 显示网格模拟 flex-wrap
- vue.js - D3更新条形图VUE.js
- haskell - 具有类型默认值的类型注释的函数组合
- c++ - 如何从其他线程winapi获取消息
- javascript - Javascript 显示 windows.VARIABLE 然后它设置
- r - 包含自定义函数的 R apply() 函数问题
- python - 将 value_counts() 的索引添加到 groupby 中每个组的新列
- c++ - 如何实现阻塞处理循环?
- python - Python 引用整数变量
- data-distribution-service - 将 FastRTPS 用于命令和控制应用程序