Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

javascript - 使用jQuery创建新元素的首选方法(The preferred way of creating a new element with jQuery)

I've got 2 ways I can create a <div> using jQuery .(我有两种方法可以使用jQuery创建一个<div> 。)

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?(使用除可重用性之外的第二种方式有什么缺点?)   ask by Ashwin translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.(当然.html('*')会覆盖内容,而.append('*')则不会,但我猜,这不是你的问题。) Another good practice is prefixing your jQuery variables with $ :(另一个好的做法是使用$前缀jQuery变量:)
Is there any specific reason behind using $ with variable in jQuery(在jQuery中使用$ with variable有什么特别的原因吗?) Placing quotes around the "class" property name will make it more compatible with less flexible browsers.(在"class"属性名称周围放置引号将使其与不太灵活的浏览器更兼容。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...