本文介绍了通过 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?

推荐答案

一些注意事项:

  • 使用 innerHTML 在 IE 中更快,但在 chrome + firefox 中更慢.这是一个基准,用一组不断变化的<div>s +

    s;这里是一个基准,展示了一个恒定的、简单的

    .
    • 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);
    }
    

    如果parent 包含descendant,这将返回true.像这样测试:

    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 标签附加字符串,哪个更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    07-31 17:11