通过onclick事件,我试图将多个LI添加到UL,无论我执行多少appendChilds,都不会使用这种方法添加多个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>
您每次必须创建一个单独的元素。
试试这个:
var form = document.getElementById("form");
function newLi() {
return document.createElement("li");
}
newButton.addEventListener("click", function(){
//Create a separate <ul> each time, give it a class, and add it.
var newUl = document.createElement("ul");
newUl.class = "formList";
form.appendChild(newUl);
//create new <li>'s and append them
formList.appendChild(newLi());
formList.appendChild(newLi());
formList.appendChild(newLi());
//smile. :D
}
与穆罕默德不同,我假设您想<ul>
每次创建一个单独的无序列表()。
因此,每当单击按钮时,我们都会添加一个新值<ul>
,然后将<li>
s追加到新值中<ul>
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句