简体   繁体   中英

HTML - Button is cancelled only after second click

I have a very simple code: I want to cancel a button after it's clicked to display something else. I tried this way

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

What happens is the button gets cancelled only if I click it two times. Where did I get wrong? I'm sorry if this is a repost, I tried to check but didn't find a quetion identical to mine

It appears as if your code is going to remove the button once you click on it. Is this correct, or are we not looking at the full markup?

try this:

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

container.childNodes[0] is a text Node, in which the text is Newline

I gave id to the button and removed it using id. In your case it is not removing in first time because container.childNodes[0] in first time is not a button. Try your self using console.log in your function.

 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> 

Alternatively, you could do this:

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

No separate JS file needed.

If you remove \\n (ie new line ) your code will work

try like this

 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> 

The reason why your code is not working is, when you hit enter after div , HTML DOM will automatically creates one dummy text node as it's child. hence your input node became the second child for your container .

Working fiddle

Hope it helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM