javascript - 请解释附加文档片段发生了什么

标签 javascript dom

我想知道这里发生了什么。我有一个文档片段(来自模板),我将该片段附加到 Dom (document.body)。在这样做之前,我获得了对所有片段的子项的引用,并在控制台中将其注销。然后我对同一个数组执行 append 和 console.log,它现在是空的。

有人知道这里发生了什么吗?为什么在附加片段后该数组现在为空。

<html>
<body>

<template id="templateEl">
  <div>Div Content</div><span>Span Content</span>
</template>

<script>

var el = document.querySelector("#templateEl");
var fragment = document.importNode(el.content, true);
var children = fragment.children;

console.log(children);
document.body.appendChild(fragment);
console.log(children);

</script>
</body>
</html>

最佳答案

当您使用importNode() 方法时,您正在创建元素的副本,作为document fragment。 .

由于您将 true 作为导入方法(第三个)的 deep 参数传递,因此该片段包含复制元素的子元素。所以你可以正确地记录它。

但是,当您将此片段附加到正文时,子项将从片段中提取出来,并附加到所选元素(在您的情况下为正文):

(from MDN's docs)

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.

由于 fragment 变量是对片段的引用,因此其 children 属性变为空。

关于javascript - 请解释附加文档片段发生了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31191822/

相关文章:

java - 不分割获取url参数

javascript - 相当于 jQuery eq 方法的原型(prototype)

javascript - 使用 AngularJS 重定向到新页面

javascript - 当元素位于触发器之外时,Javascript 显示出现问题

javascript - 在 html 页面的 iframe 内显示警告框

html - 用于 cms (Weebly) 小部件(图库)的 CSS 内联样式覆盖

Javascript 在数组中添加/删除类只能工作一次

javascript - jQuery:连接隐藏表并将列插入到另一个表中

javascript - 使 Google 可视化 API 从 https ://charts. googleapis.com/* 而不是 http ://charts. apis.google.com/* 返回呈现的可视化

javascript - 在打开下拉列表/动态更新下拉列表之前等待元素加载