javascript - 使用javascript将多个Li添加到Ul

标签 javascript

通过 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.

Description at MDN

关于javascript - 使用javascript将多个Li添加到Ul,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39283670/

相关文章:

javascript - 是否可以将 animate 与 jQuery 的属性一起使用?

javascript - Rails - 使用 javascript 创建的远程链接

javascript - 伪造预加载器屏幕

javascript - 源映射错误 : request failed with status 404 Resource URL: http://{mywebsite}/js/app. js 源映射 URL : bootstrap. js.map-laravel-Vue

php - Html 组合框到数据库记录 ID

javascript - 使用函数和返回值设置 "d"时如何修复 d3 解析错误?

javascript - 从 JS 客户端在 SignalR 控制台应用程序上进行身份验证

JavaScript 对象镜像/单向属性同步

javascript - 在 CSS 中是否可以通过单击另一个元素来更改元素的样式?

javascript - HTML 敏捷包忽略输入斜杠