代码之家  ›  专栏  ›  技术社区  ›  derekantrican

已覆盖click事件的addEventListener

  •  0
  • derekantrican  · 技术社区  · 3 年前

    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! . 我哪里出错了?

    1 回复  |  直到 3 年前
        1
  •  0
  •   brk    3 年前

    它与变量的作用域有关。 addEventListener 将添加一个事件,此时虽然会触发回调,但循环已完成其执行& 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>