尝试使用按钮单击事件删除列表项,但列表仅在第二次单击后删除。
<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);
};
发布于 2018-07-30 03:01:28
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>
发布于 2018-07-30 03:05:23
将.lastChild更改为.lastElementChild,您的函数将正常工作。最后一个子节点是一个文本节点,包含空格、制表符和回车符,最后一个元素是您想要的元素。
发布于 2018-07-30 03:00:25
试试下面的
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>
https://stackoverflow.com/questions/51583525
复制相似问题