哪些 jQuery 方法可在 jQuery 创建元素调用的对象参数中使用?
约翰·雷西格 (John Resig) 发帖于: http://ejohn.org/apps/workshop/adv-talk/#3 说我可以使用对象参数附加方法。
“text”似乎工作得很好,但对象中的其他任何内容都会作为属性添加到元素中。
我可以附加任何其他方法吗?
$("<li/>", {
click: function(){},
id: "test", // mix ids and jQuery methods
class: "clickable"
});
或者这是解决方案吗?
$("<li/>")
.click(function(){})
.attr("id","test")
.addClass("clickable");
John Resig post at:
http://ejohn.org/apps/workshop/adv-talk/#3
says I can attach methods using the object parameter.
'text' seems to work just fine, but anything else in the object is added as an attribute to the element.
Are there any other methods I can attach to this?
$("<li/>", {
click: function(){},
id: "test", // mix ids and jQuery methods
class: "clickable"
});
or is this the solution?
$("<li/>")
.click(function(){})
.attr("id","test")
.addClass("clickable");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
浏览 jQuery 源代码,看起来 @Neal 几乎是正确的。看来使用语法
相当于调用:
其中
true
是一个(未记录?)参数,告诉.attr()
调用中指定的 jQuery 函数config
键(如果它们列在$.attrFn
中)。$.attrFn
列表(至少在 jQuery 1.6.4 中)包含以下函数:因此 config 对象可以包含表示属性名称的键及其值(默认值)或上面列出的任何函数名称,他们的第一个论点。我认为 Resig 在将
addClass
显示为配置对象中的键时存在拼写错误,因为正如您所注意到的,这只会生成一个名为“addclass”的属性。Looking through the jQuery source, it looks like @Neal is almost right. It appears that using the syntax
is equivalent to calling:
where
true
is an (undocumented?) parameter telling.attr()
to call the jQuery functions named in theconfig
keys IF they are listed in$.attrFn
. The$.attrFn
list (at least in jQuery 1.6.4) includes the following functions:So the
config
object can contain either keys representing attribute names, with their values (the default) or any of the function names listed above, with their first argument. I think Resig has a typo when he showsaddClass
as a key in his config object, because as you note, this just produces an attribute with the name "addclass".我刚刚测试了这两种方法。两种方法产生相同的结果(HTML 代码、DOM 属性),而第二种方法的速度是后者的两倍。
测试用例:
I have just tested both methods. Both approaches produce the same result (HTML code, DOM properties), while the second option is twice as fast.
Testcase:
我认为很明显,考虑到简单的性能优势结果,似乎没有太多情况使用第二个参数对象来定义元素。
正如 John Resig 还指出的那样,这也可以用于复杂的创建:
我的假设是这样会更慢,但我发现这个示例更具可读性,并且允许完整的 jQuery 方法支持而不是子集由@nrabinowitz 提到。
I think it's clear given the simple performance advantage results that there doesn't seem to be much of a case to use the second parameter object to define the element.
As John Resig also points out, this can also be used for complex creation:
My assumption was that it would be slower this way, but I find this example to be more readable, as well as allowing for full jQuery method support instead of the subset mentioned by @nrabinowitz.