使用for循环设置事件处理程序 [英] Setting event handlers using a for loop
问题描述
我搞乱了一些javascript,在jsfiddle,并遇到一个奇怪的问题。我似乎无法弄清楚为什么我无法通过for循环设置 onclick
事件处理程序:
I was messing around with some javascript, on jsfiddle, and ran into a strange issue. I can't seem to figure out why I am unable to set onclick
event handlers via a for loop:
html:
<table border="1" cellspacing="1" width="500">
<tr id="headerRow">
<td>Header1</td>
<td>Header2</td>
<td>Header3</td>
<td>Header4</td>
</tr>
<tr>
<td>books</td>
<td>red</td>
<td>peas</td>
<td>321</td>
</tr>
<tr>
<td>tapes</td>
<td>blue</td>
<td>jello</td>
<td>654</td>
</tr>
</table>
在DOM中执行的js:
js executed in DOM ready:
var arr = document.getElementById('headerRow')
.getElementsByTagName("td");
// Why does this work??
/*arr[0].onclick = function() { alert(arr[0].innerHTML); };
arr[1].onclick = function() { alert(arr[1].innerHTML); };
arr[2].onclick = function() { alert(arr[2].innerHTML); };
arr[3].onclick = function() { alert(arr[3].innerHTML); };
*/
//But this doesn't????
for(var i = 0; i < arr.length; i++) {
arr[i].onclick = function() { alert(arr[i].innerHTML); };
}
推荐答案
i
不会包含你想要的当前索引,而是最后一个值 i
c $ c> arr.length
i
will not contain the "current index" like you are intending, but rather the last value i
was, ie arr.length
一个快速肮脏的解决方案是做这样的事
One quick n dirty solution would be to do something like this
for(var i = 0; i < arr.length; i++) {
(function(_i){
arr[_i].onclick = function() { alert(arr[_i].innerHTML); };
})(i);
}
这样做是为了捕获 i的当前值在您正在执行的语句的闭包内的一个新变量
_i
中,因此它将留在周围并成为您期望的值每次调用onclick处理程序。
what this does is captures the current value of i
in a new variable _i
within the closure of the statement you're executing, so it'll stay around and be the value you'd expect every time your onclick handler is called.
这篇关于使用for循环设置事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!