假设我有一个包含重复值的链接列表,如下所示:
Say I have a list of links with duplicate values as below:
<a href="#">Book</a> <a href="#">Magazine</a> <a href="#">Book</a> <a href="#">Book</a> <a href="#">DVD</a> <a href="#">DVD</a> <a href="#">DVD</a> <a href="#">Book</a>我将如何使用 JQuery 删除 dups 并留下以下示例:
How would I, using JQuery, remove the dups and be left with the following for example:
<a href="#">Book</a> <a href="#">Magazine</a> <a href="#">DVD</a>基本上,我正在寻找一种方法来删除找到的任何重复值并显示每个链接的 1 个.
Basically I am looking for a way to remove any duplicate values found and show 1 of each link.
推荐答案 var seen = {}; $('a').each(function() { var txt = $(this).text(); if (seen[txt]) $(this).remove(); else seen[txt] = true; });说明:
seen 是一个将任何先前看到的文本映射到 true 的对象.它作为一个 集合 包含所有以前看到的文本.if (seen[txt]) 行检查文本是否在集合中.如果是这样,我们之前已经看过这段文字,所以我们删除了链接.否则,这是我们第一次看到的链接文本.我们将其添加到集合中,以便删除具有相同文本的任何进一步链接.
seen is an object which maps any previously seen text to true. It functions as a set containing all previously seen texts. The line if (seen[txt]) checks to see if the text is in the set. If so, we've seen this text before, so we remove the link. Otherwise, this is a link text we see for the first time. We add it to the set so that any further links with the same text will be removed.
表示集合的另一种方法是使用包含所有值的数组.但是,这会使其速度变慢,因为要查看数组中是否有值,我们每次都需要扫描整个数组.相比之下,使用 seen[txt] 在对象中查找键非常快.
An alternative way to represent a set is to use an array containing all values. However, this would make it much slower since to see if a value is in the array we'd need to scan the entire array each time. Looking up a key in an object using seen[txt] is very fast in comparison.
更多推荐
JQuery:删除重复元素?
发布评论