更好的是,通过DOM函数附加新元素,或使用HTML标记附加字符串? [英] What is better, appending new elements via DOM functions, or appending strings with HTML tags?

查看:165
本文介绍了更好的是,通过DOM函数附加新元素,或使用HTML标记附加字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了几种不同的方法来添加DOM元素。例如,最流行的似乎是,例如,

I have seen a few different methods to add elements to the DOM. The most prevelent seem to be, for example, either

document.getElementById('foo').innerHTML ='<p>Here is a brand new paragraph!</p>';

newElement = document.createElement('p');
elementText = document.createTextNode('Here is a brand new parahraph!');
newElement.appendChild(elementText);
document.getElementById('foo').appendChild(newElement);

但我不知道做任何一个的优势。有没有一个经验法则是什么时候应该在另一个完成,还是其中一个只是平淡不妥?

but I'm not sure of the advantages to doing either one. Is there a rule of thumb as to when one should be done over the other, or is one of these just flat out wrong?

推荐答案

p>一些注释:

  • Using innerHTML is faster in IE, but slower in chrome + firefox. Here's one benchmark showing this with a constantly varying set of <div>s + <p>s; here's a benchmark showing this for a constant, simple <table>.

另一方面,DOM方法是传统的标准 - innerHTML 在HTML5中标准化,并允许您保留对新创建的元素的引用,以便稍后对其进行修改。

On the other hand, the DOM methods are the traditional standard -- innerHTML is standardized in HTML5 -- and allow you to retain references to the newly created elements, so that you can modify them later.

因为innerHTML是快速(足够),简洁易用,对于每一种情况都很有吸引力。但请注意,使用 innerHTML 从文档中分离所有现有的DOM节点。以下是您可以在此页面上测试的示例。

Because innerHTML is fast (enough), concise, and easy to use, it's tempting to lean on it for every situation. But beware that using innerHTML detaches all existing DOM nodes from the document. Here's an example you can test on this page.

首先,让我们创建一个功能,让我们测试一个节点是否在页面上:

First, let's create a function that lets us test whether a node is on the page:

function contains(parent, descendant) {
    return Boolean(parent.compareDocumentPosition(descendant) & 16);
}

这将返回 true 如果 parent 包含 descendant 。测试如下:

This will return true if parent contains descendant. Test it like this:

var p = document.getElementById("portalLink")
console.log(contains(document, p)); // true
document.body.innerHTML += "<p>It's clobberin' time!</p>";
console.log(contains(document, p)); // false
p = document.getElementById("portalLink")
console.log(contains(document, p)); // true

这将打印:

true
false
true

它可能不像我们使用 innerHTML 应该会影响我们对 portalLink 元素的引用,但它确实如此。需要重新检索才能正常使用。

It may not look like our use of innerHTML should have affected our reference to the portalLink element, but it does. It needs to be retrieved again for proper use.

这篇关于更好的是,通过DOM函数附加新元素,或使用HTML标记附加字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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