如何扩展jQuery以便更容易检索tagName [英] How to extend jQuery to make it easier to retrieve the tagName
问题描述
我希望扩展jQuery,以便我可以轻松地检索jQuery对象中第一个元素的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());
任何想法有什么问题?
BTW ,我希望将它用于测试而不是生产。
BTW, I'm looking to use this more for testing than in production.
推荐答案
请尝试这样做:
$.fn.tagName = function() {
return this.get(0).tagName;
}
alert($('#testElement').tagName());
为了解释原始示例无效的原因, each()
方法将始终返回原始jQuery对象(除非jQuery对象本身被修改)。要查看每个代码中发生的情况,这里有一些伪代码,显示每个()
方法的工作原理:
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;
}
这不是每个()
真的得到实现(可能是长镜头),但它是为了显示 action()
函数的返回值被忽略。
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.
这篇关于如何扩展jQuery以便更容易检索tagName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!