通过 onclick 事件,我试图将多个 LI 添加到 UL,无论我添加多少个 appendChild,它都不会使用此方法添加多个 LI。
var form = document.getElementById("form");
var newUl = document.createElement('ul');
var newLi = document.createElement('li');
newButton.addEventListener("click", function(){
form.appendChild(newUl);
newUl.id = "formList";
var formList = document.getElementById("formList");
formList.appendChild(newLi);
formList.appendChild(newLi);
formList.appendChild(newLi);
}
//// html
<div id="form">
</div>
最佳答案
newLi 是对您希望附加到 formList 的节点的引用。它只能存在一次。
因此,第一次执行 formList.appendChild(newLi) 时,它会将其附加到 formList。第二次执行时,它将从第一个位置移除,现在添加到第二个位置。第三名也是如此。
您不能使用 appenChild 多次追加同一个节点。
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node). This means that a node can't be in two points of the document simultaneously. So if the node already has a parent, the node is first removed, then appended at the new position.
关于javascript - 使用javascript将多个Li添加到Ul,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39283670/