Jquery无法理解这一点

Tom*_*len 3 javascript jquery

alert(i)的onclick绑定线3个div的运行,但所有的人都当点击警报的最后一组值i.我希望我想做的事情有道理,很难解释.它不会警告1,2或3,而是警告3,3,3.

// Updates bar preview box
this.updatePropertyMarkerBox = function(self, BarsID) {

    ... snip ...

    // Loop  and add event handler
    for (var i = 0; i < self.bars[BarsIndex].markers.length; i++) {

        // Add click event
        $("#bmi-" + self.containerId + "-" + i).bind('click', function() {
            alert(i);
        });
    }
Run Code Online (Sandbox Code Playgroud)

Rob*_*ert 5

当你在for循环中进行迭代时,你基本上给了i的地址,如果你在那个时刻在for循环中使用它,它将是预期的值,但是如果你以后使用它(比如一个click事件)它将指向最终递增的值3.为了获得所需的效果,你可以创建一个匿名函数,就像这样

for (var i = 0; i < self.bars[BarsIndex].markers.length; i++) (function(i) {

    // Add click event
    $("#bmi-" + self.containerId + "-" + i).bind('click', function() {
        alert(i);
    });
})(i)
Run Code Online (Sandbox Code Playgroud)