【问题标题】:jQuery select all items with same IDjQuery选择具有相同ID的所有项目
【发布时间】:2013-11-04 05:08:47
【问题描述】:

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

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

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

ps。我找到了this,但这假设您知道 ID 是什么。

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    您可以使用.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);
    });
    

    演示:Fiddle

    【讨论】:

    • 它将改变类的所有元素,而不仅仅是那些ID重复的元素。
    【解决方案2】:

    首先为所有具有相同 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()

    【讨论】:

      【解决方案3】:

      您可以做的是遍历该类的所有元素,并使用相同的 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')开头。

      【讨论】:

        【解决方案4】:

        你必须确保你没有覆盖原来的 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/

        编辑:also, in a plugin form 这样你就可以链接它$('.foo').fixDupes().css('color', 'red');

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多