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')但无济于事。

小提琴

在附加动作发生时,应保留带有值’sample’的输入。

使用jqueryfilter:gt(0)排除第一个元素。

 $('[id]').each(function () { $('[id="' + this.id + '"]:gt(0)').remove(); }); 

或者选择所有可用元素,然后使用.slice(1)排除第一个元素。

 $('[id]').each(function (i) { $('[id="' + this.id + '"]').slice(1).remove(); }); 

尝试:

  $('[id="' + this.id + '"]:not(#" + this.id + ":first)').remove(); 

你可以试试

 $("#ID").nextAll().remove(); 

此代码比其他代码长,但双嵌套循环应该使其操作显而易见。

这种方法的优点是它只需要扫描DOM以生成具有id属性一次的元素列表,然后使用相同的列表来查找(和删除)重复项。

已删除的元素将具有parentNode === null因此可以在迭代数组时跳过。

 var $elems = $('[id]'); var n = $elems.length; for (var i = 0; i < n; ++i) { var el = $elems[i]; if (el.parentNode) { // ignore elements that aren't in the DOM any more var id = el.id; for (var j = i + 1; j < n; ++j) { var cmp = $elems[j]; if (cmp.parentNode && (cmp.id === id)) { $(cmp).remove(); // use jQuery to ensure data/events are unbound } } } } 

试试这个

 var duplicated = {}; $('[id]').each(function () { var ids = $('[id="' + this.id + '"]'); if ( ids.length <= 1 ) return ; if ( !duplicated[ this.id ] ){ duplicated[ this.id ] = []; } duplicated[ this.id ].push( this ); }); // remove duplicate last ID, for elems > 1 for ( var i in duplicated){ if ( duplicated.hasOwnProperty(i) ){ $( duplicated[i].pop() ).remove(); } } 

和jsfiddle是http://jsfiddle.net/z4VYw/5/

 $('[id]').each(function() { var $ids = $('[id=' + this.id + ']'); if ($ids.length > 1) { if(this.id === your_id)//which is duplicating $ids.not(':first').remove(); } }); 

我使用not()ids删除当前元素并删除其余元素:

( 小提琴 )

 $('body').on("click", ".placeholder", function() { data = '
'; $('form').append(data); // ideally I'd like to run this function after append but after googling I find that's not possible. // for each ID ... $('[id]').each(function () { var ids = $('[id="' + this.id + '"]'); if (ids.length>1) { ids.not(this).remove(); } return; }); });

尝试使用以下function对我来说工作正常:

  $('#favourities-ajax ul li').each(function(i) { $('[id="' + this.id + '"]').slice(1).remove(); });