首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么javascript中的click事件仅在second clik上删除列表项

为什么javascript中的click事件仅在second clik上删除列表项
EN

Stack Overflow用户
提问于 2018-07-30 02:54:14
回答 4查看 96关注 0票数 2

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

代码语言:javascript
复制
    <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
复制
let lostLives = function() {
    let lives = document.getElementById('lives');
    lives.removeChild(lives.lastChild);
};
EN

回答 4

Stack Overflow用户

发布于 2018-07-30 03:01:28

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

您需要lastElementChild,它只为您提供元素。

代码语言:javascript
复制
let lostLives = function() {
    let lives = document.getElementById('lives');
    lives.removeChild(lives.lastElementChild);
};
代码语言:javascript
复制
<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>

票数 2
EN

Stack Overflow用户

发布于 2018-07-30 03:05:23

将.lastChild更改为.lastElementChild,您的函数将正常工作。最后一个子节点是一个文本节点,包含空格、制表符和回车符,最后一个元素是您想要的元素。

票数 2
EN

Stack Overflow用户

发布于 2018-07-30 03:00:25

试试下面的

代码语言:javascript
复制
let lostLives = function() {
  let lives = document.getElementById('lives');
  lives.removeChild(lives.lastElementChild);
};
代码语言:javascript
复制
<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>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51583525

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档