javascript - 添加新的
- 问题
问题描述
这是我的 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>
为什么脚本只执行 1 次插入新元素,尽管我放入了 2 次(insertBefore 和 appendChild)?
当我尝试添加多个 'appendChild()' 方法时,只添加了 1 个新元素,这是为什么呢?
解决方案
您试图在两个地方添加相同的节点,所以最后一个获胜。该节点实际上被添加到末尾,但立即移动到开头。
您可以克隆节点,并将克隆插入到开头:
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>
推荐阅读
- javascript - TypeError:exports.property 不是函数
- google-colaboratory - 如何运行直到在 google colab 中选择包含的单元格?
- c# - sqlparameters.Add(或 AddWithValue)的结果
- spring-boot - Vaadin 14 Spring Boot App 从 ProductionMode 的命令行运行
- azure-data-factory - ADF - 将 csv 从源复制到目标,如果它在 2 天内完成并实现较旧的目标版本
- linux - 如何在 csh 脚本中忽略第一行并从第二行文本文件中读取和存储值
- python - 无法在珊瑚开发板上运行 edgetpu 检测
- python - Django allauth 设置会话参数并在登录后获取它们的问题
- python - 用于从数据集中过滤数据的 Python pandas 或 lambda 实用程序
- javascript - 从 reduce [Angular] 返回对象