使用 jQuery 过滤多个 <ul> 列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9375079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filter multiple <ul> lists with jQuery
提问by Dante
I have multiple lists on one page (multiple categories of products) like this:
我在一个页面上有多个列表(多个类别的产品),如下所示:
<h3>Category 1</h3>
<ul id="category1">
<li>item1</li>
<li>item2</li>
<li>item3</li>
</ul>
<h3>Category 2</h3>
<ul id="category2">
<li>item27</li>
<li>item28</li>
</ul>
The amount of lists is variable.
列表的数量是可变的。
I would like a filter like on the demo page here http://static.railstips.org/orderedlist/demos/quicksilverjs/jquery.html.
我想要一个像http://static.railstips.org/orderedlist/demos/quicksilverjs/jquery.html的演示页面上的过滤器。
But it should search over the different lists.
但它应该搜索不同的列表。
If the user searches for "2" then the result should be:
如果用户搜索“2”,那么结果应该是:
<h3>Category 1</h3>
<ul id="category1">
<li>item2</li>
</ul>
<h3>Category 2</h3>
<ul id="category2">
<li>item27</li>
<li>item28</li>
</ul>
If he searches for "1" then it should be (don't show h3 title for list where there are no results):
如果他搜索“1”,那么它应该是(不要在没有结果的列表中显示 h3 标题):
<h3>Category 1</h3>
<ul id="category1">
<li>item1</li>
</ul>
Can someone help me?
有人能帮我吗?
Thanks in advance!
提前致谢!
回答by Johan
How about something like this:
这样的事情怎么样:
HTML
HTML
<input type="text" />
<ul id="category1">
<li>item1</li>
<li>item2</li>
<li>item3</li>
</ul>
<ul>
<li>item27</li>
<li>item28</li>
</ul>
JS
JS
$(function(){
$('input[type="text"]').keyup(function(){
var searchText = $(this).val();
$('ul > li').each(function(){
var currentLiText = $(this).text(),
showCurrentLi = currentLiText.indexOf(searchText) !== -1;
$(this).toggle(showCurrentLi);
});
});
});
http://jsfiddle.net/EFTZR/146/
http://jsfiddle.net/EFTZR/146/
Another solution using filter(), which is mentioned below:
使用filter() 的另一种解决方案,如下所述:
$('input[type="text"]').keyup(function(){
var that = this, $allListElements = $('ul > li');
var $matchingListElements = $allListElements.filter(function(i, li){
var listItemText = $(li).text().toUpperCase(),
searchText = that.value.toUpperCase();
return ~listItemText.indexOf(searchText);
});
$allListElements.hide();
$matchingListElements.show();
});
回答by Jesse van Assen
You can do this with the filter method in jQuery:
您可以使用 jQuery 中的 filter 方法执行此操作:
var valueToSearch = "item1"; // this one should come from the search box
var allListItems = $("ul > li");
var filteredItems = allListItems.filter(function(index) {
var listItemValue = $(this).text();
var hasText = listItemValue.indexOf(valueToSearch) > -1;
return hasText;
});
Next, you can display the values in the filteredItems variable in a list or something like that, using a for loop.
接下来,您可以使用 for 循环以列表或类似的方式显示 filtersItems 变量中的值。