请解释附加文档片段时发生的情况

时间:2015-07-02 18:17:01

标签: 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>

1 个答案:

答案 0 :(得分:0)

当您使用 List<string> folderNames = new List<string>(); folderNames.Add("Folder 1"); folderNames.Add("Folder 2"); folderNames.Add("Folder 3"); ClientContext context = new ClientContext("https://sharepoint.Site/Test"); List list = context.Web.Lists.GetByTitle("Documents"); var folder = list.RootFolder; context.Load(folder); context.ExecuteQuery(); foreach (string folderName in folderNames) { ListItemCreationInformation newItemInfo = new ListItemCreationInformation(); newItemInfo.UnderlyingObjectType = FileSystemObjectType.Folder; newItemInfo.LeafName = folderName; ListItem newListItem = list.AddItem(newItemInfo); newListItem["Title"] = folderName; newListItem.Update(); } context.ExecuteQuery(); 方法时,您将创建该元素的副本,作为document fragment

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

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

(from MDN's docs)

  

其他各种方法可以将文档片段作为参数(例如,任何Node接口方法,如Node.appendChild和Node.insertBefore),在这种情况下, 片段的子节点被追加或插入,而不是片段本身。

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