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

why a click event in javascript is removing a list item on second clik only

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

    <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);
};

试试这个

var lostLives = document.getElementById("lostLives");

lostLives.addEventListener("click", function(){
    var el = document.getElementById('lives');
    if (el.children.length > 0) {  
       el.removeChild(el.lastElementChild);
    }else{
        alert("All items have been deleted");
    }
});
    <section class="score-panel">

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

试试下面的

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>

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>

lastChild is not element but text node. You should be using lastElementChild as you are trying to remove li element node.

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>

将 .lastChild 更改为 .lastElementChild,您的函数将起作用。最后一个子节点是带有空格制表符和回车符的文本节点 returns,最后一个元素是您想要的。

为了演示为什么每按两次键都会删除一次,请将您的脚本更改为:

let lives = document.getElementById('lives');
console.log(lives);
let lostLives = function() {
    lives.removeChild(lives.firstElementChild);
};

如果您在浏览器中查看您的页面并打开控制台,您可以查看子节点如下:

您会注意到有 7 个节点,而不是预期的 3 个,因为文本和元素节点是 ul#lives 的子节点。从底部开始,首先是一个文本节点,因此在按下按钮时将删除它,然后是 li 元素,然后是文本等,这正是您所看到的。

再举一个例子,如果您将 html 更改为如下:

<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>

然后你会发现只有3个子节点,你的函数会按你预期的那样工作。

希望对您有所帮助。