如何按多个项目搜索/过滤列表? [英] How to search/filter list by multiple items?
问题描述
我正在寻找一个示例,或者可能是一个方法,通过键入文本框的多个项目来过滤/搜索项目列表。
I'm looking for an example or maybe a little hint for a method to filter/search list of items by multiple items typed into textbox.
让我们假设我有一个清单:
Let's assume that I have a list :
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
<li>Water</li>
<li>Juice</li>
</ul>
我想要的是输入(在文本框中)例如:Milk; Water; Juice
(中间有分号),返回三个项目。
What I want is to type (in textbox) for instance : Milk;Water;Juice (with semicolon between), which returns three items.
$('li').filter(function() {
????
})
它可能是一个过滤器或另一个jquery / js function。
It could be a filter or another jquery/js function.
提前感谢您的任何帮助
编辑:
我忘了告诉它应该按最后一项的一部分进行搜索。例如Coffe; Te - >返回Coffe和Tea
I forget to tell that it should search by a part of last item. For instance Coffe;Te --> return Coffe and Tea
推荐答案
这是一种可以实现此目的的方法: -
This is one way you can achieve this:-
$('input').keyup(function(){
var search = this.value.split(';');
$('ul li').each(function(index, element){
$(element).toggle(search.indexOf($(element).text()) >= 0);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
<li>Water</li>
<li>Juice</li>
</ul>
拆分;
上的搜索输入并检查每个li的文本以查看它是否在数组中。
Split the search input on ;
and check the text of each li to see if it is in the array.
更新
忽略大小写和部分匹配
$('input').keyup(function() {
var search = this.value.split(';');
$('div label').each(function(index, element) {
var text = $(element).text().toLowerCase();
var show = search.filter(function(e) {
return e != '' && text.indexOf(e.toLowerCase()) >= 0;
}).length > 0;
$(element).toggle(show);
});
});
div label {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<div>
<label>
<input class="appFilterCheckbox" id="appFilterCheckbox" type="checkbox" value="Coffee" />Coffee</label>
<br/>
<label>
<input class="appFilterCheckbox" id="appFilterCheckbox" type="checkbox" value="Tea" />Tea</label>
<br/>
<label>
<input class="appFilterCheckbox" id="appFilterCheckbox" type="checkbox" value="Milk" />Milk</label>
<br/>
<label>
<input class="appFilterCheckbox" id="appFilterCheckbox" type="checkbox" value="Water" />Water</label>
<br/>
<label>
<input class="appFilterCheckbox" id="appFilterCheckbox" type="checkbox" value="Juice" />Juice</label>
</div>
这篇关于如何按多个项目搜索/过滤列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!