Javascript 使用 jQuery 添加 DOM 元素的最佳方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2202269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to add DOM elements with jQuery
提问by sdr
So I've seen three ways to add html/DOM elements to a page. I'm curious what the pros and cons are for each of them.
所以我已经看到了三种向页面添加 html/DOM 元素的方法。我很好奇它们各自的优缺点是什么。
1 - Traditional JavaScript
1 - 传统 JavaScript
I believe the straight JS way to do it is by constructing each element, setting attributes, and then appending them. Example:
我相信直接的 JS 方法是构造每个元素,设置属性,然后附加它们。例子:
var myRow = document.createElement("tr");
myRow.class = "myClass";
var firstTD = document.createElement("td");
firstTD.innerHTML = "first";
myRow.appendChild(firstTD);
var secondTD = document.createElement("td");
secondTD.innerHTML = "second";
myRow.appendChild(secondTD);
document.getElementById("myContainer").appendChild(myRow);
2 - Appending a string of html via jQuery
2 - 通过 jQuery 附加一串 html
I've noticed that most jQuery examples I see usually just append a string of html.
Example:
我注意到我看到的大多数 jQuery 示例通常只是附加一串 html。
例子:
$("#myContainer").append('<tr class="myClass"><td>first</td><td>second</td></tr>');
3 - jQuery's .clone()
3 - jQuery 的 .clone()
I've also seen a lot of uses and references to .clone() in jQuery.
Example:
我还在 jQuery 中看到了很多对 .clone() 的使用和引用。
例子:
$("#myContainer").append($(".myClass").Clone());
I'd love to hear what others have to say about this.
我很想听听其他人对此有何看法。
(Also, this seems like a good candidate for a 'community wiki', but I'm not too familiar with them. Will someone comment and let me know if it should be? Thanks)
(此外,这似乎是“社区维基”的一个不错的候选者,但我对它们不太熟悉。有人会发表评论并告诉我是否应该这样做吗?谢谢)
回答by sp.
If you are using jQuery 1.4 the best way is the following:
如果您使用的是 jQuery 1.4,最好的方法如下:
$("<a/>", {
id: 'example-link',
href: 'http://www.example.com/',
text: 'Example Page'
}).appendTo("body");
回答by jhchen
If you already have a template element that you want to copy then by all means use clone().
如果您已经有一个要复制的模板元素,那么一定要使用 clone()。
But if you want to create an element from scratch then there's basically two methods which I think you alluded to:
但是如果你想从头开始创建一个元素,那么我认为你提到的基本上有两种方法:
- Create DOM elements as objects (using createElement for example).
- Create DOM elements as HTML (using innerHTML or jQuery's html() for example).
- 将 DOM 元素创建为对象(例如使用 createElement)。
- 将 DOM 元素创建为 HTML(例如,使用 innerHTML 或 jQuery 的 html())。
First if either of the methods is more intuitive or easier to write for you, I'd recommend just doing that.
首先,如果任何一种方法对您来说更直观或更容易编写,我建议您直接这样做。
Otherwise benefits of using the latter is that it is cleaner if the element has many children. For example, try to make a table row with 6 columns, each with a different class using the first method. Your code will be much longer than if you used the second method.
否则使用后者的好处是,如果元素有很多子元素,它会更干净。例如,尝试使用第一种方法创建一个包含 6 列的表格行,每列具有不同的类。您的代码将比使用第二种方法时长得多。
As far as performance goes this is a good guide http://andrew.hedges.name/experiments/innerhtml/but the short answer is for most cases the differences are quite negligible. A good guide for performance in general as well is: http://www.artzstudio.com/2009/04/jquery-performance-rules/. The 6th tip has to do with DOM manipulation.
就性能而言,这是一个很好的指南http://andrew.hedges.name/experiments/innerhtml/但简短的回答是在大多数情况下差异可以忽略不计。一个很好的一般性能指南是:http: //www.artzstudio.com/2009/04/jquery-performance-rules/。第 6 个技巧与 DOM 操作有关。
回答by Re_p1ay
You can try this:
你可以试试这个:
$("<div/>", {
// PROPERTIES HERE
text: "Click me",
id: "example",
"class": "myDiv", // ('class' is still better in quotes)
css: {
color: "red",
fontSize: "3em",
cursor: "pointer"
},
on: {
mouseenter: function() {
console.log("PLEASE... "+ $(this).text());
},
click: function() {
console.log("Hy! My ID is: "+ this.id);
}
},
append: "<i>!!</i>",
appendTo: "body" // Finally, append to any selector
});
回答by Mike Sherov
If you have jQuery already available, use it. If you don't want to host it, use Google's hosted version. In the end is it always calling the native javascript createElement or innerHTML methods anyway. So I'd use #2, and #3 if I specifically had to clone an existing element on the page.
如果您已经有可用的 jQuery,请使用它。如果您不想托管它,请使用 Google 的托管版本。最终它总是调用原生的 javascript createElement 或 innerHTML 方法。因此,如果我特别需要克隆页面上的现有元素,我会使用 #2 和 #3。
回答by Clarence Liu
If you're working with large amounts of HTML you want to reuse then I'd suggest you look at: http://api.jquery.com/jQuery.template/which is final, but will be replaced by something better.
如果您正在处理大量要重用的 HTML,那么我建议您查看:http: //api.jquery.com/jQuery.template/,这是最终版本,但会被更好的内容取代。
I use it in a production environment and it's great, as for smaller pieces of html what sp. said is the best way
我在生产环境中使用它,它很棒,至于较小的html什么sp。说是最好的方法
回答by pradeep
Clone existing Content...
克隆现有内容...
var $html = $template.clone();
$html.find(''); ///after change content...
Because of clone content is with 'DOM' properties. Then u can change this tags,properties,value then append it..
因为克隆内容具有“DOM”属性。然后你可以改变这个标签,属性,值然后附加它..
回答by Teja Kantamneni
The cleaner way to do is using jQuery.
更简洁的方法是使用 jQuery。
$('tr').addClass('myClass')like syntax. This is easy to read, understand and maintain.
$('tr').addClass('myClass')像语法。这很容易阅读、理解和维护。

