点击事件的addEventListener被覆盖

addEventListener for click event is overwritten

我是 HTML/JS 的新手,正在努力学习所有的怪事。在尝试让它工作的过程中,我了解到只允许一个 Element.onclick = function() {},如果你尝试添加更多,之前的将被覆盖。但是现在我通过使用 Element.addEventListener("click", function() {}) 面临着同样的事情。这是我的代码:

<html>
<body id="body">

</body>
</html>
<script>
  window.onload = function() {
    for (var buttonText of ["item1", "item2", "item3"]){
      var button = document.createElement("button");
      button.textContent = buttonText;
      button.addEventListener("click", function(){
        console.log(`${buttonText} was clicked!`);
      });
      document.getElementById("body").append(button);
    }
  }
</script>

无论点击哪个按钮,控制台总是显示item3 was clicked!。我哪里错了?

与变量的作用域有关。 addEventListener 将添加一个事件,虽然回调将触发但循环已完成它的执行时间 & buttonText 将更新为最新值。这导致 buttonText 总是 item3。一种选择是将 for (var buttonText of ["item1", "item2", "item3"]) { 替换为 for (let buttonText of ["item1", "item2", "item3"]) {

window.onload = function() {
  for (let buttonText of ["item1", "item2", "item3"]) {
    let button = document.createElement("button");
    button.textContent = buttonText;
    button.addEventListener("click", function() {
      console.log(`${buttonText} was clicked!`);
    });
    document.getElementById("body").append(button);
  }
}
<div id='body'></div>

另一种选择是您可以创建一个 closure 和一个 IIFE

window.onload = function() {
  for (var buttonText of ["item1", "item2", "item3"]) {
    // start of IIFE
    (function(txt) {
      var button = document.createElement("button");
      button.textContent = txt;
      button.addEventListener("click", function() {
        console.log(`${txt} was clicked!`);
      });
      document.getElementById("body").append(button);

    }(buttonText))

  }
}
<div id='body'></div>