简体   繁体   English

添加新的<li>元素成<ul>问题</ul></li>

[英]Adding new <li> element into <ul> Questions

this is my html code这是我的 html 代码

 function addChildren() { var el = document.getElementById('one'); //Create new node and textNode var newEl = document.createElement('li'); var newText = document.createTextNode('New Node Text'); //Append as child Node newEl.appendChild(newText); newEl.setAttribute('class', 'hot'); //Append as child Node to the last of list el.appendChild(newEl); //Append as child node to the beginning of list el.insertBefore(newEl, el.firstChild); } document.querySelector('#add'). addEventListener('click', addChildren);
 <ul id='one'> <li class='hot'>Hello</li> <li class='hot'>World</li> <li class='hot'>This</li> <li class='hot'>Is</li> <li class='hot'>Ben!</li> </ul> <button id="add">Add</button>

Why is the script only executing 1 insertion of the new element, although I put in 2 (insertBefore and appendChild)?为什么脚本只执行 1 次插入新元素,尽管我输入了 2 次(insertBefore 和 appendChild)?

And when I tried adding multiple 'appendChild()' method, only 1 new element is added, why is this?当我尝试添加多个 'appendChild()' 方法时,只添加了 1 个新元素,这是为什么呢?

You are trying to add the same node in two places, so the last one wins.您试图在两个地方添加相同的节点,所以最后一个获胜。 The node is actually added to the end, but immediately moved to the start.该节点实际上被添加到末尾,但立即移动到开头。

You canclone the node, and insert the clone to the start:您可以克隆节点,并将克隆插入到开头:

 function addChildren() { var el = document.getElementById('one'); //Create new node and textNode var newEl = document.createElement('li'); var newText = document.createTextNode('New Node Text'); //Append as child Node newEl.appendChild(newText); newEl.setAttribute('class', 'hot'); //Append as child Node to the last of list el.appendChild(newEl); // create a clone of the node var clone = newEl.cloneNode(true); //Append the clone as child node to the beginning of list el.insertBefore(clone, el.firstChild); } document.querySelector('#add'). addEventListener('click', addChildren);
 <ul id='one'> <li class='hot'>Hello</li> <li class='hot'>World</li> <li class='hot'>This</li> <li class='hot'>Is</li> <li class='hot'>Ben!</li> </ul> <button id="add">Add</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM