通过for循环绑定的事件中的数值错误

use*_*040 2 javascript alert for-loop

var rows = document.getElementsByClassName('row');
for (var i = 0, l = rows.length; i < l; i++) {
    if (i % 2 === 0) {
        $(rows[i]).click(function () {
            alert('I am line number ' + i);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

嗨,我怎样才能获得每一行的实际行号?因为当我在偶数行上触发click事件时我得到的所有内容都会被警告上限值(即:rows.length = 7,i对于每一行点击将为6).

Vis*_*ioN 8

问题是,在click触发事件时,i循环迭代已经改变了变量.从理论上讲,你可以使用闭包来使事情有效,即

for (var i = 0, l = rows.length; i < l; i++) {
    if (i % 2 === 0) {
        (function(i) {
            $(rows[i]).click(function() {
                alert("I am line number " + i);
            });
        )(i);
    }
}
Run Code Online (Sandbox Code Playgroud)

实际上,如果你使用jQuery(我从代码中理解),使用:even选择器更容易:

$(".row:even").click(function() {
    alert("I am line number " + $(".row").index(this));
});
Run Code Online (Sandbox Code Playgroud)