javascript - 为什么javascript中的点击事件仅在第二次点击时删除列表项

标签 javascript removechild

尝试使用按钮单击事件删除列表项,但列表仅在第二次单击后才被删除。

    <section class="score-panel">

    <ul id="lives">
        <li>life11</li>
        <li>life2</li>
        <li>life3</li>
    </ul>
    <button onclick="lostLives()">Remove list item</button>
    </section>

javascript 函数看起来像

let lostLives = function() {
    let lives = document.getElementById('lives');
    lives.removeChild(lives.lastChild);
};

最佳答案

lastChild will give you text nodes or comment nodes ,而不仅仅是元素节点。在本例中,它为您提供了一个与最后一个 <li> 之后的空白相对应的文本节点。 .

你想要lastElementChild , 它只给你元素。

let lostLives = function() {
    let lives = document.getElementById('lives');
    lives.removeChild(lives.lastElementChild);
};
<section class="score-panel">

  <ul id="lives">
    <li>life11</li>
    <li>life2</li>
    <li>life3</li>
  </ul>
  <button onclick="lostLives()">Remove list item</button>
</section>

关于javascript - 为什么javascript中的点击事件仅在第二次点击时删除列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51583525/

相关文章:

javascript - javascript中的页面生命周期

javascript - 为什么 removeChild 需要父节点?

javascript - 如何使用所述列表项上的按钮删除列表项

javascript - 将removeChild与HTMLCollection结合使用

xcode - EnumerateChildNodesWithName 中的多个子节点

javascript - 如何在 div 中附加和删除图像(javascript 和 html)

javascript - Parse Cloud 代码迭代结果问题

javascript - Google 折线图 - 自动刷新数据库

javascript - D3 : What is a Bisector?

javascript - 指令隔离范围 1.2.2