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");
最佳答案
查看 jQuery 源代码,@Neal 看起来几乎是对的。似乎使用语法
$(htmlCode, config);
相当于调用:
$(htmlCode).attr(config, true);
true
是一个(未记录?)参数,告诉 .attr()
调用在 config
键中命名的 jQuery 函数,如果它们列在 $.attrFn
中。 $.attrFn
列表(至少在 jQuery 1.6.4 中)包括以下函数:
val, css, html, text, data, width, height, offset, blur, focus, focusin, focusout, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error
因此 config
对象可以包含表示属性名称的键及其值(默认值)或上面列出的任何函数名称及其第一个参数。我认为 Resig 在他的配置对象中将 addClass
显示为键时有错别字,因为正如您所注意到的,这只会产生一个名为“addclass”的属性。
关于javascript - 哪些 jQuery 方法可用于 jQuery 创建元素调用的对象参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7437525/