尝试使用按钮单击事件删除列表项,但列表仅在第二次单击后才被删除。
<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/