jQuery:找到重复的ID并删除除第一个之外的所有ID [英] jQuery: Finding duplicate ID's and removing all but the first
本文介绍了jQuery:找到重复的ID并删除除第一个之外的所有ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$('[id]').each(function () {
var ids = $('[id="' + this.id + '"]');
// remove duplicate IDs
if (ids.length > 1 && ids[0] == this) $('#' + this.id).remove();
});
以上将删除第一个重复ID,但我想删除最后一个。我已经尝试 $('#'+ this.id +':last')
但无济于事。
The above will remove the first duplicate ID, however I want to remove the last. I've tried $('#'+ this.id + ':last')
but to no avail.
在小提琴中当附加动作发生时,应该保留值'sample'的输入。
In the fiddle the input with the value 'sample' should be kept when the append action takes place.
推荐答案
使用jquery过滤器:gt(0)
排除第一个元素。
Use jquery filter :gt(0)
to exclude first element.
$('[id]').each(function () {
$('[id="' + this.id + '"]:gt(0)').remove();
});
或选择所有可用元素,然后使用 .slice排除第一个元素(1)
。
Or select all the available elements, then exclude the first element using .slice(1)
.
$('[id]').each(function (i) {
$('[id="' + this.id + '"]').slice(1).remove();
});
这篇关于jQuery:找到重复的ID并删除除第一个之外的所有ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文