用jQuery添加DOM元素的最佳方式 [英] Best way to add DOM elements with jQuery

查看:113
本文介绍了用jQuery添加DOM元素的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我已经看到了三种添加html / DOM元素到页面的方式。我很好奇他们每个人的利弊。

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 - 传统JavaScript

我相信直接的JS方式是通过构造每个元素,设置属性,然后附加它们。
示例:

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 - 通过jQuery追加一串html

我注意到,我看到的大多数jQuery示例通常只是附加一串html。

示例:

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的.clone()

我也在jQuery中看到很多用途和参考.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)

推荐答案

如果您使用的是jQuery 1.4,最好的方法是:

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");

这篇关于用jQuery添加DOM元素的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆