jQuery删除重复的元素 [英] jQuery remove duplicated element

查看:104
本文介绍了jQuery删除重复的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果dom生成重复的相同元素怎么办?例如:

What if dom generates duplicated same elements? for example:

    <ul id="listitem">
     <li>item1</li>
    </ul>

    <ul id="listitem">
     <li>item1</li>
    </ul>

    <ul id="listitem">
     <li>item1</li>
    </ul>

...

然后可以保留其中之一并删除另外两个吗?

Then is this possible to keep one of them and delete extra two?

推荐答案

ID应该是唯一的,以防万一该ID由外部代码呈现并且您无法控制它,则唯一的选择是遍历所有ul并删除重复的ul.

ID should be unique, in case if this getting rendered by external code and you don't have control over it then your only choice is to iterate over all ul and remove ul that are duplicates.

var duplicateChk = {};

$('ul[id]').each (function () {
    if (duplicateChk.hasOwnProperty(this.id)) {
       $(this).remove();
    } else {
       duplicateChk[this.id] = 'true';
    }
});

这篇关于jQuery删除重复的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆