使用 jQuery 创建新元素的首选方式 [英] The preferred way of creating a new element with jQuery
问题描述
我有两种方法可以使用 jQuery
创建
要么:
var div = $("");$("#box").append(div);
或者:
$("#box").append("");
除了可重用性之外,使用第二种方式的缺点是什么?
第一个选项给你更多的灵活性:
var $div = $("", {id: "foo", "class": "a"});$div.click(function(){/* ... */});$("#box").append($div);当然 .html('*')
覆盖内容而 .append('*')
没有,但我想,这不是你的问题.
另一个好的做法是在你的 jQuery 变量前加上 $
:
在 jQuery 中将 $ 与变量一起使用是否有任何具体原因
在 "class"
属性名称周围加上引号将使其与不太灵活的浏览器更兼容.
I've got 2 ways I can create a <div>
using jQuery
.
Either:
var div = $("<div></div>");
$("#box").append(div);
Or:
$("#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);
And of course .html('*')
overrides the content while .append('*')
doesn't, but I guess, this wasn't your question.
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屋!
查看全文