循环中有多个不同的事件侦听器

Multiple different event listeners in for loop

本文关键字:事件 侦听器 循环      更新时间:2023-09-26

下面的代码总是返回undefined。为什么会这样?我希望事件侦听器使用索引的字符串进行响应。

感谢

var array = ["Hey", "Hi", "Hello"];
for (var i = 0; i < array.length; i++) {
  var box = document.createElement("div");
  box.className = "box";
  box.addEventListener("click", function() {
    alert(array[i]);
  }, false);
}

这个问题经常被问到。JavaScript没有块作用域。只有在调用函数时才会创建变量范围。因此,要将i的范围扩大到当前循环迭代,需要在创建处理程序的函数调用中引用它。

// Create a function that returns a function
function createHandler(i) {
    // The value of `i` is local to this variable scope
    // Return your handler function, which accesses the scoped `i` variable
    return function() {
        alert(array[i]);
    }
}

var array = ["Hey", "Hi", "Hello"];
for (var i = 0; i < array.length; i++) {
  var box = document.createElement("div");
  box.className = "box";
  // Invoke the `createHandler`, and pass it the value that needs to be scoped.
  // The returned function will use its reference to the scoped `i` value.
  box.addEventListener("click", createHandler(i), false);
}

我强烈建议您使用命名函数,而不是流行的内联函数调用。它可能更高效,函数名称提供了有关函数用途的文档。

您需要将点击处理程序包装在一个闭包中,以创建i:的本地副本

box.addEventListener("click", (function(i) { 
  return function() {
    alert(array[i]);
  }
})(i), false);

Fiddle

按照现在的代码,i的值为3,而array[3]当然是未定义的。上面创建了值为0、1、2的i的3个副本。

可能最简单的解决方案是:

box.addEventListener("click", alert.bind(window, array[i]), false);

但这在IE<9.