下面我有一个小的 JavaScript 文件,旨在为数组中的每个数组创建元素。一切正常,除了最后一个功能,removeEventListeners()
. 此函数不会返回任何错误,但它只是不会删除侦听器。
非常感谢任何帮助!谢谢。
var array = [["Bob", 17, 1], ["Alan", 16, 1], ["Dave", 19, 1], ["Terry", 5, 1], ["Janet", 23, 0]];
var elements = [];
var AGE = 1;
function createHandler(i) {
return function() {
// Upon clicking the element show an alert with the age of that element (taken from array)
alert(array[i][AGE]);
}
}
for (var i = 0; i < array.length; i++) {
elements[i] = document.createElement("div");
elements[i].addEventListener("click", createHandler(i), false);
}
// This function is where the problem lies - it doesn't remove the handlers
function removeEventListeners() {
for (var i = 0; i < elements.length; i++) {
elements[i].removeEventListener("click", createHandler(i), false);
}
}