简体   繁体   中英

Why do I have to double-click on my button to make the event work?

Is simple, i'm starting with javascript. I wrote down an example for the 'removeChild' method, with simple function that activates with a button. But, I have to double-click on it to make it works.

I guess that this could be solved using JQuery, but I just want to understand what's happening, and try to figure out what is javascript understanding.

This is my HTML:

 function remove() { var parent = document.getElementById("demo"); var child = parent.lastChild; parent.removeChild(child); } 
 <div id="demo"> <p>Paragraph 1</p> <p>Paragraph 2</p> <p>Paragraph 3</p> </div> <button onClick="remove()">Erase last</button> 

lastChild includes text nodes. Because you have a line-break after the last <p> , your first click actually removes the line-break . The subsequent click removes the <p> element.

To demonstrate, take a look at this example, where I've simply removed the line-breaks from your HTML:

 function remove() { var parent = document.getElementById("demo"); var child = parent.lastChild; parent.removeChild(child); } 
 <div id="demo"><p>Paragraph 1</p><p>Paragraph 2</p><p>Paragraph 3</p></div> <button onClick="remove()">Erase last</button> 

However, removing line-breaks from your HTML is hardly a practical solution!

Instead, replace lastChild with lastElementChild :

 function remove() { var parent = document.getElementById("demo"); var child = parent.lastElementChild; parent.removeChild(child); } 
 <div id="demo"> <p>Paragraph 1</p> <p>Paragraph 2</p> <p>Paragraph 3</p> </div> <button onClick="remove()">Erase last</button> 

With parent.childNodes you can find all child nodes of the div

NodeList(6) [text, p, text, p, text, p]

Click every twice you can remove ap element.

Not double-click.

Reference link: https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes

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