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
146 views
in Technique[技术] by (71.8m points)

javascript - Best way to add DOM elements with jQuery

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.

1 - Traditional JavaScript

I believe the straight JS way to do it is by constructing each element, setting attributes, and then appending them. Example:

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

I've noticed that most jQuery examples I see usually just append a string of html.
Example:

$("#myContainer").append('<tr class="myClass"><td>first</td><td>second</td></tr>');

3 - jQuery's .clone()

I've also seen a lot of uses and references to .clone() in jQuery.
Example:

$("#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)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you are using jQuery 1.4 the best way is the following:

$("<a/>", {
    id: 'example-link',
    href: 'http://www.example.com/',
    text: 'Example Page'
}).appendTo("body");

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

...