gpt4 book ai didi

javascript - appendChild() 从导入的模板中剥离内容

转载 作者:行者123 更新时间:2023-11-29 21:14:59 25 4
gpt4 key购买 nike

我获得了 HTML5 的事件副本 <template>使用函数 importNode() :

  function getTemplate() {
var t = document.getElementById("example");
return document.importNode(t.content,true);
}

在此之后,我填充动态数据,

  var t = fillTemplate({
id:"test",
text:"Enter test data"
});

最后,我将节点附加到目标容器中:

  var c = document.getElementById("container");
var result = c.appendChild(t);

我的问题:result节点的所有内容都被剥离:我无法访问结果节点中模板的组件元素。实际上,result一旦 appendChild 节点不包含任何子节点已执行操作。

我期望 appendChild 的返回值应该指向已插入到容器中并且现在是事件文档的一部分的节点。任何解释为什么不是这种情况?

这是 jsfiddle(在 Chrome 53 中测试):

https://jsfiddle.net/rplantiko/mv2rbhym/

最佳答案

这是因为您操作的不是Node,而是DocumentFragment

如果您想获得插入的节点数,您应该在父容器上执行调用(在您的示例中为 c),然后您将得到正确的答案 (5)。

但如果只想统计自己添加的子元素,则不应该使用childNodes,而是ParentNode接口(interface)的属性children:

c.childNodes.length  // = 5
c.children.length // = 2

添加到容器 c 后,DocumentFragment t 不再有子项。

来自MDN documentation :

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 at the location in the DOM where you insert the document fragment, not the fragment itself. The fragment itself continues to exist (in memory) but now has no children.

DOM 3 W3C recommendation也很清楚:

Furthermore, various operations -- such as inserting nodes as children of another Node -- may take DocumentFragment objects as arguments; this results in all the child nodes of the DocumentFragment being moved to the child list of this node.

关于javascript - appendChild() 从导入的模板中剥离内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39815979/

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