抱歉这个非常基本的JQuery问题。我创建了'mytest'jquery函数,如下所示:
jQuery.fn.mytest = function () {
alert($(this).attr('id'))
}
现在,如果我这样称呼它,一切都很完美:
$("#someid").mytest();
警告“someid”。但如果我做这样的事情:
$("#someid, #anotherid, #moreids").mytest();
此功能仅警告“someid”。当然存在“另一个”和“更多”。
为什么mytest()不起作用,这个函数的代码是什么?
答案 0 :(得分:5)
您的代码正在为jQuery添加一个“插件”,使您的函数可用于jQuery实例。您在函数中只看到一个ID的原因是您正在使用attr
,它只检索第一个元素的属性。 (另外,真的不需要attr
来获取id
值。)
您的功能应如下所示(live copy):
jQuery.fn.mytest = function () {
var ids = jQuery.map(this, function(elm) {
return elm.id;
});
alert(ids.join(","));
};
...显示当前匹配集合中每个元素的id
值(如果有)。
或者您可以使用简单的循环而不是jQuery.map
(live copy)来执行此操作:
jQuery.fn.mytest = function () {
var ids, index, elm;
ids = [];
for (index = 0; index < this.length; ++index) {
elm = this[index];
if (elm.id) {
ids.push(elm.id);
}
}
alert(ids.join(","));
};
另外,请注意,在jQuery插件函数中,this
是当前的jQuery实例,因此您不需要(或想要)通过$()
传递它来创建jQuery包装器元素周围(你在事件处理程序中执行,而不是插件)。因此,当我在上面的第二个示例中执行this.length
时,我正在使用我们当前正在操作的jQuery实例的length
属性。当我使用括号表示法(this
)索引elm = this[index];
时,我正在索引到jQuery实例的匹配元素集(如get
方法,但更直接)。
答案 1 :(得分:3)
这是由于.attr()
:
获取匹配元素集中第一个元素的属性值。 (我的重点)
决议:
.attr()
方法仅获取匹配集中 first 元素的属性值。要单独获取每个元素的值,请使用循环结构,例如jQuery的.each()
或.map()
方法。
如,
jQuery.fn.mytest = function () {
var ids = [];
$(this).each(function() {
ids.push($(this).attr('id'));
});
alert(ids);
}
(未经测试,另见Utilizing the awesome power of jQuery to access properties of an element。)
<强>声明强>
这正是.map()
的用途。阅读以上内容作为想法的演示,而不是实现所述想法:)
答案 2 :(得分:3)
您需要使用
jQuery.fn.mytest = function () {
return this.each(function(){
alert(this.id);
});
}
阅读http://docs.jquery.com/Plugins/Authoring,其中介绍了尝试创建插件时需要了解的内容。
使用 return this.each(..)
可以对您的插件进行链接,以便您$('#something, #somethingelse').mytest().hide();
答案 3 :(得分:0)
您正在选择多个元素,因此......您还需要遍历这些元素以提醒每个ID。现在你只得到第一个id。所以应该是这样的:
jQuery.fn.mytest = function () {
return $(this).each(function(){
alert($(this).attr('id'));
});
}
未经测试......