Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 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 Reply

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"属性名称周围放置引号将使其与不太灵活的浏览器更兼容。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...