Javascript事件监听器只能工作一次

时间:2017-10-17 01:43:28

标签: javascript

我无法理解为什么以下代码只运行一次。任何帮助将非常感激。现在被困在这个上几天了:



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);
&#13;
<!DOCTYPE html>
<html>
<body>
  <head><script src="script.js" defer></script></head>
<button id="myBtn">Try it</button>
</body>
</html>
&#13;
&#13;
&#13;

提前致谢!!

2 个答案:

答案 0 :(得分:0)

来自@nnnnnnn,

  

不要使用body.innerHTML + = ...来添加元素,因为这样   覆盖整个现有主体,实际上重新创建DOM

您可以在自己的身体中添加一个类似此<div id="msg"></div>的新div,以显示按钮点击事件消息。

&#13;
&#13;
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);
&#13;
<!DOCTYPE html>
<html>
<body>
  <head><script src="script.js" defer></script></head>
<button id="myBtn">Try it</button>
<div id="msg"></div>
</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你正在通过body.innerHTML +=来训练你所附的听众。以下是您可以尝试阻止的内容:

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

insertAdjacentHTML快速可靠。

您也可以尝试appendChild,但这意味着您要追加HTMLElement