为什么javascript中的click事件仅删除第二个clik上的列表项

时间:2018-07-29 18:54:14

标签: 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);
};

6 个答案:

答案 0 :(得分:2)

perf record ptr_vector,而不仅仅是元素节点。在这种情况下,它为您提供了与最后一个lastChild之后的空白相对应的文本节点。

您想要<li>,它只为您提供元素。

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

答案 1 :(得分:2)

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

答案 2 :(得分:1)

尝试以下一个

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>

答案 3 :(得分:1)

  

lastChild不是元素,而是text节点。尝试删除lastElementChild元素节点时,应使用li

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>

答案 4 :(得分:1)

为了演示为什么每隔两下按键会删除一次,请将脚本更改为此:

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

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

enter image description here

您会注意到有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个子节点,并且您的功能将按预期工作。

我希望这会有所帮助。

答案 5 :(得分:0)

尝试一下

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>