为什么onClick删除子元素需要被单击两次?

时间:2019-05-25 06:38:00

标签: javascript dom

我想删除列表中的第一个孩子,这个动作是按钮的onclick事件,onclick方法是:list.removeChild(list.firstItem)。但是,我必须单击两次按钮才能看到效果,为什么

我发现example可以通过调用item.parentNode.removeChild(item)删除列表中的第一项。 问题是,当我将处理程序方法更改为list.removeChild(list.firstChild)时,我需要单击两次以查看效果。

我已经尝试过list.removeChild(list.firstChildElement),并且按预期方式工作(第一项通过单击消失),为什么list.removeChild(list.firstChild)相比,此方法不需要双击方法。

示例:

  • HTML:
<ul id="list">
  <li id="first">Coffee</li>
</ul>

<button onclick="removeLi()">Remove li</button>
  • 一键查看效果:
// 1:
let item = document.getElementById("first");
function removeLi() {
  item.parentNode.removeChild(item);
}
// 2:
const list = document.getElementById("list");
function removeLi() {
  list.removeChild(list.firstChildElement);
}
  • 需要双击:
const list = document.getElementById("list");
function removeLi() {
  list.removeChild(list.firstChild);
}

0 个答案:

没有答案
相关问题