简体   繁体   English

HTML-仅在第二次单击后按钮才会取消

[英]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: HTML:

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

js: 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 container.childNodes[0]是文本节点,其中文本是Newline

I gave id to the button and removed it using id. 我将id赋予按钮,并使用id将其删除。 In your case it is not removing in first time because container.childNodes[0] in first time is not a button. 对于您而言,它不是第一次删除,因为第一次的container.childNodes [0]不是按钮。 Try your self using console.log in your function. 使用功能中的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> 

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. 无需单独的JS文件。

If you remove \\n (ie new line ) your code will work 如果您删除\\n (即换行 ),则代码将起作用

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. 代码无法正常工作的原因是,当您在div之后按enter时,HTML DOM将自动创建一个虚拟文本节点作为其子节点。 hence your input node became the second child for your container . 因此,您的input节点成为container第二个子节点。

Working fiddle 工作提琴

Hope it helps :) 希望能帮助到你 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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