JQuery:删除重复元素?

编程入门 行业动态 更新时间:2024-10-11 15:14:16
本文介绍了JQuery:删除重复元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个包含重复值的链接列表,如下所示:

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:删除重复元素?

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

发布评论

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

>www.elefans.com

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