Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

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

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:

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

Any ideas what's wrong?

BTW, I'm looking to use this more for testing than in production.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...