簡體   English   中英

HTML-僅在第二次單擊后按鈕才會取消

[英]HTML - Button is cancelled only after second click

我有一個非常簡單的代碼:單擊某個按鈕以顯示其他內容后,我想取消一個按鈕。 我這樣嘗試

HTML:

<div id="container">
    <input type="button" value="New game" onclick="newGame()" />
</div>

js:

function newGame() {
    var container = document.getElementById("container");
    container.removeChild(container.childNodes[0]);
}

發生的情況是只有單擊兩次按鈕才能取消按鈕。 我在哪里弄錯了? 很抱歉,如果這是轉貼,我嘗試檢查但找不到與我相同的問題

似乎您的代碼將在您單擊按鈕后將其刪除。 這是正確的,還是我們不看完整的標記?

嘗試這個:

function newGame() {
    var container = document.getElementById("container");
    // change 0 to 1
    container.removeChild(container.childNodes[1]);
} 

container.childNodes[0]是文本節點,其中文本是Newline

我將id賦予按鈕,並使用id將其刪除。 對於您而言,它不是第一次刪除,因為第一次的container.childNodes [0]不是按鈕。 使用功能中的console.log嘗試自己。

 function newGame() { var container = document.getElementById("container"); var d_nested = document.getElementById("button_1"); var throwawayNode = container.removeChild(d_nested); //container.innerHTML=''; } 
 <div id="container"> <input id="button_1" type="button" value="New game" onclick="newGame()" /> </div> 

或者,您可以這樣做:

<div id="container">
<input type="button" value="New game" onclick="document.getElementById('container').removeChild(this);" />

無需單獨的JS文件。

如果您刪除\\n (即換行 ),則代碼將起作用

這樣嘗試

 function newGame() { var container = document.getElementById("container"); debugger; container.removeChild(container.childNodes[0]); } 
 <div id="container"><input type="button" value="New game" onclick="newGame()" /></div> 

代碼無法正常工作的原因是,當您在div之后按enter時,HTML DOM將自動創建一個虛擬文本節點作為其子節點。 因此,您的input節點成為container第二個子節點。

工作提琴

希望能幫助到你 :)

暫無
暫無

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

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