How to extend jQuery to make it easier to retrieve the tagName

前端 未结 4 498
不思量自难忘°
不思量自难忘° 2020-12-06 09:32

I am looking to extend jQuery so I can easily retrieve the tagName of the first element in a jQuery object. This is what I have come up with, but it doesn\'t seem to work:

4条回答
  •  死守一世寂寞
    2020-12-06 10:33

    Try this instead:

    $.fn.tagName = function() {
        return this.get(0).tagName;
    }
    alert($('#testElement').tagName());
    

    To explain a little bit more of why your original example didn't work, the each() method will always return the original jQuery object (unless the jQuery object itself was modified). To see what is happening in each with your code, here is some pseudocode that shows how the each() method works:

    function each(action) {
        for(var e in jQueryElements) {
            action();
        }
        return jQueryObject;
    }
    

    This is not how each() really gets implemented (by a long shot probably), but it is to show that the return value of your action() function is ignored.

提交回复
热议问题