簡體   English   中英

為什么javascript中的click事件僅在第二個clik上刪除列表項

[英]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);
};

lastChild 將為您提供文本節點或注釋節點 ,而不僅僅是元素節點。 在這種情況下,它為您提供了與最后一個<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更改為.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不是元素而是text節點。 在嘗試刪除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> 

為了說明為什么每次按鍵都會刪除,請將腳本更改為:

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個子節點,你的功能將按預期工作。

我希望這有幫助。

嘗試這個

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM