我获得了 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 中测试):
最佳答案
这是因为您操作的不是 Node
而是 DocumentFragment
。
如果您想获取插入的节点数量,您应该对父容器(示例中的 c
)执行调用,然后您将得到正确的答案 (5)。
但是如果只想统计自己添加的子元素,就不应该使用childNodes
,而应该使用ParentNode接口(interface)children
的属性:
c.childNodes.length // = 5
c.children.length // = 2
追加到容器 c
后,DocumentFragment t
不再有子级。
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.
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/