简体   繁体   中英

Javascript Event Listener only works one time

I'm having trouble understanding why the following code only runs one time. Any help would be much appreciated. Been stumped on this one for a couple days now:

 const button = document.querySelector("#myBtn"); var clickCount = 0; function myFunction() { clickCount++; document.body.innerHTML += "<br><br>Button was clicked " + clickCount + " time(s)"; console.log("Button was clicked " + clickCount + " time(s)"); } button.addEventListener("click", myFunction, false); 
 <!DOCTYPE html> <html> <body> <head><script src="script.js" defer></script></head> <button id="myBtn">Try it</button> </body> </html> 

Thanks in advance!!

From @nnnnnnn,

Don't use body.innerHTML += ... to add elements, because this overwrites the entire existing body and in effect recreates the DOM

You can add a new div like this <div id="msg"></div> in your body that will show your button click event messages.

 const button = document.querySelector("#myBtn"); var clickCount = 0; function myFunction() { clickCount++; document.getElementById('msg').innerHTML += "<br><br>Button was clicked " + clickCount + " time(s)"; console.log("Button was clicked " + clickCount + " time(s)"); } button.addEventListener("click", myFunction, false); 
 <!DOCTYPE html> <html> <body> <head><script src="script.js" defer></script></head> <button id="myBtn">Try it</button> <div id="msg"></div> </body> </html> 

You are nuking the listener you attached by doing body.innerHTML += . Here is what you can try to prevent that:

document.body.insertAdjacentHTML('beforeend', "<br><br>Button was clicked " + clickCount + " time(s)");

insertAdjacentHTML is fast and reliable.

You can also try appendChild but that would mean you have an HTMLElement to append.

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