JavaScript数组的addEventListener [英] Javascript Array addEventListener
问题描述
在美国的形状按钮互动式地图,每个按钮都有状态缩写为一个id,一个按钮被点击/州时,我想触发功能stateSelect,并用它,所以我知道发状态缩写什么一直pssed $ p $。为什么不下面的工作?
Interactive map with buttons in the shape of states, each button has the state abbreviation as an id, when a button/state is clicked I would like to fire the function "stateSelect" and send the state abbreviation with it so I know what's been pressed. Why doesn't the following work?
var stateList = new Array("AK","AL","AR","AS","AZ","CA","CO","CT","DC","DE","FL","GA","GU","HI","IA","ID",
"IL","IN","KS","KY","LA","MA","MD","ME","MH","MI","MN","MO","MS","MT","NC","ND","NE","NH","NJ","NM","NV","NY",
"OH","OK","OR","PA","PR","PW","RI","SC","SD","TN","TX","UT","VA","VI","VT","WA","WI","WV","WY");
for (var i = 0; i < stateList.length; i++) {
document.getElementById(stateList[i]).addEventListener('mousedown', function() {stateSelect(stateList[i])}, false);
}
我显然想避免50 code的一些行,但我不知道为什么这个简单的循环是行不通的。
I obviously want to avoid 50 some lines of code but I'm not sure why this simple loop isn't working.
推荐答案
由于在处理程序运行时,它会 i的值
,这是无论它是后循环结束了。
Because when the handler runs, it looks up the value of i
, which is wherever it was after the loop finished.
您需要范围在函数I
变量:
function listenerForI( i ) {
document.getElementById(stateList[i]).addEventListener('mousedown', function() {stateSelect(stateList[i])}, false);
}
for (var i = 0; i < stateList.length; i++) {
listenerForI( i );
}
现在的 I
的处理程序引用将在参数被调用的 listenerForI
功能。因此,该 I
将引用在从为
循环传递的值。
Now the i
referenced by the handler will be the parameter to the listenerForI
function that was invoked. As such, that i
will reference the value that was passed in from the for
loop.
这篇关于JavaScript数组的addEventListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!