jQuery 选择具有相同 ID 的所有项

jQuery select all items with same ID

本文关键字:ID 选择 jQuery      更新时间:2023-09-26

我知道它不好,我知道ID是唯一的,我需要在某些页面上大规模修复它。

我不知道那些ID是什么,我只知道它的类,所以有可能以某种方式做

$('.someClass').itemsThatHasIdDuplicate().each(function(){
    $(this).attr('id', Math.random()); //its stupid to use random for ID, but shows what I mean
});

附言。我已经找到了这个,但这假设你知道 ID 是什么。

您可以使用

.attr( attributeName, function(index, attr) )执行此操作:

// Get all the items with Duplicate id
var $itemsThatHasIdDuplicate = $('[id]').filter(function () {
    return $('[id="' + this.id + '"]').length > 1;
});
// Modify the id for all of them
$itemsThatHasIdDuplicate.attr('id', function (i, val) {
    return 'newID' + (i + 1);
});

演示:小提琴

首先,向所有具有相同 id 的元素添加一些类。

$('[id]').each(function(){
  var ids = $('[id="'+this.id+'"]');
  if(ids.length>1 && ids[0]==this){
    $('#'+this.id).addClass('changeID');
}
});

然后更改具有该类的所有元素的 id...

$('.changeID').each(function(){
$(this).attr("id","changed_"+Math.random());
}

仅供参考:我建议您选择日期时间来分配id,而不是使用math.random()

您可以做的是遍历该类的所有元素,并使用相同的 ID 对这些元素进行分组。然后使用多个元素修改这些组:

var IDs = {};   
var idModifier = function(index, id) {
    return id + index;
};
$('.someClass').each(function() {
    (IDs[this.id] || (IDs[this.id] = [])).push(this);
});
$.each(IDs, function(id, elements) {
    if (elements.length > 1) {
        $(elements).prop('id', idModifier);
    }
});

这种方法的"优点"是您只搜索文档一次,开头是 $('.someClass') .

您必须确保不会覆盖原始ID

var cls = 'foo';
$('.' + cls).each(function() {
    var me = this;
    var id = $(me).attr('id');
    var dupes = $('#' + id + '.' + cls);
    dupes.each(function() {
        if(this != me) {
            $(this).attr('id', id + '_r_' + Math.random());
        }
        else {
            $(this).attr('id', id + '_o');
        }
    });
});

这样,您还可以知道每个 ID 的第一个实例是什么。

http://jsfiddle.net/g2DWR/1/

编辑:另外,在插件形式中,以便您可以将其链接$('.foo').fixDupes().css('color', 'red');