使用jQuery创建新元素的首选方法 [英] The preferred way of creating a new element with jQuery
问题描述
我有两种方法可以使用 jQuery
创建< div>
。
I've got 2 ways I can create a <div>
using jQuery
.
要么:
var div = $("<div></div>");
$("#box").append(div);
或者:
$("#box").append("<div></div>");
使用除可重用性之外的第二种方式有什么缺点?
What are the drawbacks of using second way other than re-usability?
推荐答案
第一个选项为您提供更多灵活性:
The first option gives you more flexibilty:
var $div = $("<div>", {id: "foo", "class": "a"});
$div.click(function(){ /* ... */ });
$("#box").append($div);
当然还有 .html('*')
覆盖内容而 .append('*')
没有,但我想,这不是你的问题。
And of course .html('*')
overrides the content while .append('*')
doesn't, but I guess, this wasn't your question.
另一个好的做法是在jQuery变量前加上 $
:
在jQuery中使用$ with variable有什么特别的原因吗
Another good practice is prefixing your jQuery variables with $
:
Is there any specific reason behind using $ with variable in jQuery
在类附近放置引号
属性名称将使其与不太灵活的浏览器更兼容。
Placing quotes around the "class"
property name will make it more compatible with less flexible browsers.
这篇关于使用jQuery创建新元素的首选方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!