Jquery无法理解这一点 [英] Jquery can't get my head around this

查看:91
本文介绍了Jquery无法理解这一点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

警报(i) onclick绑定行在3个div上运行,但点击时所有这些都提醒 i <的最后一个设定值/ code>。我希望我想做的事情有道理,很难解释。而不是警告1,2或3,它警报3,3,3。

The alert(i) onclick bind line is run on 3 divs, but all of them when clicked alert the last set value of i. I hope what I'm trying to do makes sense, it's hard to explain. Instead of alerting 1,2 or 3, it alerts 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);
        });
    }


推荐答案

当你在迭代时for循环,你基本上给了我的地址,如果你在那个时刻在for循环中使用它,它将是预期的值,但是如果你以后使用它(比如在点击事件中)它将指向最终递增的值3.要获得所需的效果,您可以创建一个匿名函数,如下所示

When you're iterating in the for loop, you're essentially given the address to i, if you use it within the for loop at that very moment, it will be the value expected, however if you use it later (such as in a click event) it will point to the final incremented value of 3. To get the desired affect you can create an anonymous function, like so

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)

这篇关于Jquery无法理解这一点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆