gpt4 book ai didi

javascript - 为什么添加后 DocumentFragment 被清除

转载 作者:行者123 更新时间:2023-12-03 10:02:30 24 4
gpt4 key购买 nike

第一个日志返回完整的 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 as Node.appendChild and Node.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/

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