使用JavaScript多次追加节点只能追加一次

Mar*_*ark 1 html javascript html5

为什么当我运行此示例代码时,ul列表中仅附加了一个“ A节点”?每次必须追加时都需要创建一个新节点吗?注意:使用appendNode(node.cloneNode(true))会追加多次。

let node = document.createElement("LI");
let textnode = document.createTextNode("A node");
node.appendChild(textnode);
for (let x = 0; x < 5; x++) {
  document.getElementById("myList").appendChild(node);
}
Run Code Online (Sandbox Code Playgroud)
<ul id="myList">
</ul>
Run Code Online (Sandbox Code Playgroud)

Jac*_*ord 5

这是因为您每次都附加相同的节点-将您的所有代码放入for循环中,即可正常工作:

for (let x = 0; x < 5; x++) {
  let node = document.createElement("LI");
  let textnode = document.createTextNode("A node");
  node.appendChild(textnode);
  document.getElementById("myList").appendChild(node);
}
Run Code Online (Sandbox Code Playgroud)
<ul id="myList">
</ul>
Run Code Online (Sandbox Code Playgroud)

或者,使用cloneNode

let node = document.createElement("LI");
let textnode = document.createTextNode("A node");
node.appendChild(textnode);
for (let x = 0; x < 5; x++) {
  document.getElementById("myList").appendChild(node.cloneNode(true));
}
Run Code Online (Sandbox Code Playgroud)
<ul id="myList">
</ul>
Run Code Online (Sandbox Code Playgroud)