How can I get the ID of an element using jQuery?

后端 未结 19 2615
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 11:57

Why doesn\'

19条回答
  •  忘了有多久
    2020-11-22 12:30

    Maybe useful for others that find this thread. The code below will only work if you already use jQuery. The function returns always an identifier. If the element doesn't have an identifier the function generates the identifier and append this to the element.

    var generatedIdCounter = 0;
    
    $.fn.id = function() {
        var identifier = this.attr('id');
    
        if(!identifier) {
            generatedIdCounter++;
            identifier = 'isGenerated_' + generatedIdCounter;
    
            this.attr('id', identifier);
        }
    
        return identifier;
    }
    

    How to use:

    $('.classname').id();
    
    $('#elementId').id();
    

提交回复
热议问题