简体   繁体   English

Javascript事件监听器只能运行一次

[英]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, 来自@nnnnnnn,

Don't use body.innerHTML += ... to add elements, because this overwrites the entire existing body and in effect recreates the DOM 不要使用body.innerHTML + = ...添加元素,因为这会覆盖整个现有主体,并实际上会重新创建DOM

You can add a new div like this <div id="msg"></div> in your body that will show your button click event messages. 您可以在您的正文中添加一个新的div,例如<div id="msg"></div> ,以显示按钮单击事件消息。

 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 += . 您正在通过body.innerHTML +=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. insertAdjacentHTML快速可靠。

You can also try appendChild but that would mean you have an HTMLElement to append. 您也可以尝试appendChild但这将意味着您要附加HTMLElement

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

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