无法使用removeChild()删除刚刚附加到列表的元素。只能删除开头的
这是两个按钮。一种是“appendChild”,一种是“Remove Child”。
List ----之前---------- --
一个
二
三个
附加
已附加
-------------------------
附加两个新元素后,我想删除最后一个。但是当我按下删除按钮时。
列表 ---之后-------------
一个
二
(?????????被删除)
已追加
已附加
-------------------------
附加元素仍然存在。我看到很多人用 jQuery 解决了这个问题,但我是全新的。我想知道 JavaScript 是否有解决方案。
apd.onclick = function() {
let apd = document.getElementById('apd')
let node = document.createElement('li')
node.className = 'added'
let textnode = document.createTextNode('this is node content')
node.appendChild(textnode)
document.getElementById('list').appendChild(node)
}
let list = document.getElementById('list')
let rem = document.getElementById('rem')
rem.onclick = function() {
let node = document.createElement('li')
document.getElementById('list').removeChild(list.children[0])
}
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<button id="apd">click me to append child!</button>
<button id="rem">click me to remove child!</button>
This is two button. One is "appendChild" ,One is "Remove Child".
List ----Before------------
one
two
three
appended
appended
-------------------------
After appended two new elements, I want to remove the last one. But when I press the remove button.
List ---After-------------
one
two
(?????????? be deleted)
appended
appended
-------------------------
The appended elements are still there. I see many solve this problem with jQuery, but I am totally new. I am wondering if JavaScript has the solution.
apd.onclick = function() {
let apd = document.getElementById('apd')
let node = document.createElement('li')
node.className = 'added'
let textnode = document.createTextNode('this is node content')
node.appendChild(textnode)
document.getElementById('list').appendChild(node)
}
let list = document.getElementById('list')
let rem = document.getElementById('rem')
rem.onclick = function() {
let node = document.createElement('li')
document.getElementById('list').removeChild(list.children[0])
}
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<button id="apd">click me to append child!</button>
<button id="rem">click me to remove child!</button>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
list.lastElementChild.remove();
来解决删除问题,而不是使用 onclick 事件,按照 @TJ-Crowder 在评论中的建议,使用addEventListener
,例如:参考:
removeChild
You can use
list.lastElementChild.remove();
for delete problem and instead of onclick event useaddEventListener
as suggest by @T.J- Crowder into comment like:Reference:
removeChild
on the parent instead您正在删除第一个而不是最后一个。
您可以使用 list.children[list.children.length - 1] 代替 list.children[0],这将是最后一个。
You are deleting the first one and not the last one.
Instead of list.children[0], you can use list.children[list.children.length - 1] which will be the last one.