jQuery: Finding duplicate ID's and removing all but the first

前端 未结 8 1558
天涯浪人
天涯浪人 2020-12-13 20:57
    $(\'[id]\').each(function () {

        var ids = $(\'[id=\"\' + this.id + \'\"]\');

        // remove duplicate IDs
        if (ids.length > 1 && id         


        
8条回答
  •  轮回少年
    2020-12-13 21:23

    try this

    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();            
        }
    }
    

    and jsfiddle is http://jsfiddle.net/z4VYw/5/

提交回复
热议问题