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

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

Why doesn\'

19条回答
  •  自闭症患者
    2020-11-22 12:22

    Well, seems there has not been a solution and would like to propose my own solution that is an expansion of the JQuery prototype's. I put this in a Helper file that is loaded after the JQuery library, hence the check for window.jQuery

    if (window.jQuery) {
        $.prototype.id = function () {
            if (this.length > 1) {
                var val = [];
                this.each(function (idx, el) {
                    val.push($(el).id());
                });
                return val;
            } else {
                return this.attr('id');
            }
        }
    }
    

    It may not be perfect but it is a start to maybe getting inclusion into the JQuery library.

    Returns either a single string value or an Array of string values. The Array of string values, is for the event an multi-element selector was used.

提交回复
热议问题