将过滤器添加到列表

编程入门 行业动态 更新时间:2024-10-28 08:20:56
本文介绍了将过滤器添加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复: jquery删除重复的li

Possible Duplicate: jquery remove duplicate li

我有一个类似于以下内容的列表: jsfiddle/UwPTF/

I have a List which looks like the following: jsfiddle/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'); });

更多推荐

将过滤器添加到列表

本文发布于:2023-11-09 17:21:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572972.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:过滤器   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!