将过滤器添加到列表 [英] Adding Filters to List
问题描述
可能重复:
jquery删除重复的li
Possible Duplicate:
jquery remove duplicate li
我有一个类似于以下内容的列表: http://jsfiddle.net/UwPTF/
I have a List which looks like the following: http://jsfiddle.net/UwPTF/
<ul class="uol">
<li>beta</li>
<li>gamma</li>
<li>alpha</li>
<li>beta</li>
<li>zeta</li>
<li>BETA</li>
</ul>
我有2个按钮,一个按钮突出显示重复的项目,另一个按钮移除重复的项目.
I have 2 buttons, one to highlight the items that are duplicate and the other to remove the duplicate items.
我正在尝试使用过滤器功能.如果您能解释您的代码,我们将不胜感激.
I am trying to use the filter function. If you can explain your code, it's highly appreciated.
推荐答案
HTML
<ul id="list" class="uol">
<li>beta</li>
<li>gamma</li>
<li>alpha</li>
<li>beta</li>
<li>zeta</li>
<li>BETA</li>
</ul>
<input id="find" type="button" value="Find" />
<input id="remove" type="button" value="Remove" />
JavaScript
$('#find').click(function(){
$('#list li').filter(function(){
return $(this).siblings().text().toUpperCase().indexOf($(this).text().toUpperCase()) != -1;
}).addClass('selecteditems');
});
$('#remove').click(function(){
var removed = [];
$('.selecteditems').each(function(i, item){
if($.inArray($(item).text().toUpperCase(), removed) != -1){
$(item).remove();
}
else{
removed.push($(item).text().toUpperCase());
$(item).removeClass('selecteditems');
}
});
});
单击查找"按钮时,过滤器将应用于ID为list
的无序列表中的每个<li>
项目.然后,它获取所有其他<li>
项,将其文本添加到一个字符串中并大写.然后,它检查当前<li>
项目大写时是否包含在该字符串中.如果存在,则返回true,因此将其添加到类selecteditems
.
When you click the find button, the filter gets applied to every <li>
item in your unordered list with the id list
. It then gets all of the other <li>
item's, adds their text together into one string and capitalizes it. It then checks if the current <li>
item when it is capitalized is contained in that string. If it is there, it returns true so it gets the class selecteditems
added to it.
当您单击删除按钮时,它将删除除第一个<li>
项目之外的所有类别为selecteditems
的项目,并从第一个<li>
项目中删除该类别.
When you click the remove button, it removes all but the first <li>
item with the class selecteditems
, and removes the class from the first <li>
item.
如果您要绝对确定要检查单个项目,而不是检查所有项目的字符串,则可以更改查找代码:
If you want to be absolutely sure that you are checking against individual items instead of checking against a string of all items, you can change your code for finding to this:
$('#find').click(function(){
$('#list li').filter(function(){
var sibs = [];
$.map($(this).siblings(), function(sibling){
sibs.push($(sibling).text().toUpperCase());
});
return $.inArray($(this).text().toUpperCase(), sibs) != -1;
}).addClass('selecteditems');
});
这篇关于将过滤器添加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!