如何使用闭包在JavaScript for循环中创建事件监听器? [英] How to use closures to create event listeners in a Javascript for loop?
问题描述
HTML
<span class="char" id="0">?</span>
<span class="char" id="1">!</span>
<span class="char" id="2">"</span>
<span class="char" id="3">/</span>
<span class="char" id="4">%</span>
<span class="char" id="5">$</span>
...
JavaScript
JavaScript
var charElems = document.getElementsByClassName('char');
for (var i=0; i < charElems.length; i++) {
charElems[i].addEventListener('mouseover',function() {
(function(j) {mouseoverCheck(j);}(i));
});
}
百分之百) span
元素,数字为ID(从0开始递增1)。这个循环应该为所有<$ c创建mouseover事件监听器$ c> span 元素(它们都有一个 char
类)一旦鼠标悬停,它应该优于 mouseoverCheck ()
函数并传递 i
时创建的事件侦听器。因此,203rd事件侦听器应该传入 203
。但它不。现在,它传递的是我认为的最后一个值 i
在循环完成之前。
I have a bunch (hundreds) of span
elements with numbers as IDs (starting from 0 and incrementing by 1). What this loop is supposed to do is create mouseover event listeners for all the span
elements (which all have a class of char
). Once moused over, it should excecute the mouseoverCheck()
function and pass in whatever i
was when that event listener was created. So the 203rd event listener should pass in 203
. But it does not. Right now, it passes in what I believe is the last value i
was before the loop completed.
尝试使用IIFE和闭包来确保每个事件侦听器在创建时获得 i
的值,而不是调用函数时的值。显然,我没有做到正确,但我相当肯定,关闭是我的问题的关键。任何人都可以了解如何正确地做一些光吗?我想我明白了闭合,但显然我不... ...
I was attempting to use an IIFE and closure to make sure each event listener got i
's value at the time it was created, instead of it's value when the function is called. Clearly, I didn't do it correctly, but I am fairly certain closure is the key to my problem. Can anyone shed some light on how to do this properly? I thought I understood closure, but clearly I do not...
推荐答案
它不工作,因为
charElems[i].addEventListener('mouseover',function() {
(function(j) {mouseoverCheck(j);}(i));
});
addEventListener()
在处理程序被调用的时候 i
将为6.
addEventListener()
is just assigning a handler and by the time that handler is called i
will be 6.
您应该返回一个处理程序从IIFE
you should return a handler from an IIFE
var charElems = document.getElementsByClassName('char');
for (var i=0; i < charElems.length; i++) {
charElems[i].addEventListener('mouseover', (function(temp) {
return function(){
var j = temp;
//mouseoverCheck(j);
console.log(temp);
}
}(i)));
}
这里是一个小提琴: https://jsfiddle.net/qshnfv3q/
这篇关于如何使用闭包在JavaScript for循环中创建事件监听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!