第一个日志返回完整的 li
元素,而第二个返回空 DocumentFragment
.为什么?我在任何文档中都找不到有关该行为的任何信息。
var main = document.getElementById('main');
var fooTemplate = document.getElementById('my-template');
var foo = fooTemplate.content.cloneNode(true);
console.log(foo);
main.appendChild(foo);
console.log(foo);
<template id="my-template">
<li>foo</li>
</template>
<ul id="main">
</ul>
最佳答案
From the MDN docs on DocumentFragment
Various other methods can take a document fragment as an argument (e.g., any
Node
interface methods such asNode.appendChild
andNode.insertBefore
), in which case the children of the fragment are appended or inserted, not the fragment itself.
foo = fooTemplate.content.cloneNode(true)
将文档片段复制到 foo
.main.appendChild(foo)
移动 foo
的内容文档片段到 main
. foo
仍然是一个文档片段,并且所有节点都已移动,因此它是空的。如果您想在附加 DOM 节点后保留对它们的引用,则需要存储
childNodes
, 但如果你只是引用 nodeList
,它将为空,因此您需要将其转换为 Array
:var nodes = Array.prototype.slice.call(foo.childNodes);
console.log(nodes);
main.appendChild(foo);
console.log(nodes);
关于javascript - 为什么添加后 DocumentFragment 被清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29352976/