gpt4 book ai didi

javascript - 为什么追加一个documentFragment时需要用到cloneNode?

转载 作者:数据小太阳 更新时间:2023-10-29 04:09:17 28 4
gpt4 key购买 nike

我一直在研究在 Backbone.js 应用程序中使用 documentFragments,并且想知道为什么我看到在将 documentFragment 附加到父 DOM 元素时使用“cloneNode”的示例。

例子可见here .如果您向下看 DocumentFragment 部分,您会看到:

oFrag = document.createDocumentFragment();
for (var i = 0, imax = aElms.length; i < imax; i++) {
oFrag.appendChild(aElms[i]);
}

o.innerHTML = '';
o.appendChild(oFrag.cloneNode(true));

为什么要克隆“oFrag”而不是仅仅附加它?另一个blog post不使用“cloneNode”(作为比较)。

最佳答案

你的 first link指的是blog post作者使用 document.getElementsByTagName 而不是 document.getElementById,就像在测试用例中一样。如果你想给多个元素(即:div)赋予相同的 documentFragment,你必须克隆它:

If child is a reference to an existing node in the document, appendChild moves it from its current position to the new position (i.e. there is no requirement to remove the node from its parent node before appending it to some other node).

This also means that a node can't be in two points of the document simultaneously. So if the node already has a parent, it is first removed, then appended at the new position.

通过MDN

很可能是作者(或其他人)在没有考虑到这一点的情况下复制粘贴了代码。自己尝试一下 - 您可以在没有 cloneNode 的情况下使用 appendChild,一切正常。

另一种可能性是,在 jsperf 上创建此测试用例的人不太了解准备代码的工作原理,并担心第一个测试会清空 aElms 数组,并且它将不再工作. In fact准备代码在每次定时迭代之前执行,因此无需担心其内容。

最后一件事可能是性能问题。如果你真的想测试真正的插入,你需要克隆节点。否则,您将改为测试树重新附加(请参阅上面的 MDN 链接)。

另请注意 cloning destroys event listeners .

快乐的碎片化! ;)

关于javascript - 为什么追加一个documentFragment时需要用到cloneNode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13858129/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com