Javascript jQuery闭包、循环和事件

Javascript jQuery闭包、循环和事件,javascript,jquery,loops,closures,Javascript,Jquery,Loops,Closures,我有一个类似于这里的问题:但我使用jQuery,给出的解决方案似乎是在绑定而不是单击时触发事件 这是我的密码: for(var i in DisplayGlobals.Indicators) { var div = d.createElement("div"); div.style.width = "100%"; td.appendChild(div); for(var j = 0;j<3;j++) { var test = j;

我有一个类似于这里的问题:但我使用jQuery,给出的解决方案似乎是在绑定而不是单击时触发事件

这是我的密码:

for(var i in DisplayGlobals.Indicators)
{
    var div = d.createElement("div");
    div.style.width = "100%";
    td.appendChild(div);

    for(var j = 0;j<3;j++)
    {
        var test = j;
        if(DisplayGlobals.Indicators[i][j].length > 0)
        {   
             var img = d.createElement("img");
             jQuery(img).attr({
                     src : DisplayGlobals.Indicators[i][j],
                     alt : i,
                     className: "IndicatorImage"
              }).click(
                     function(indGroup,indValue){ 
                         jQuery(".IndicatorImage").removeClass("active");
                         _this.Indicator.TrueImage = DisplayGlobals.Indicators[indGroup][indValue];
                         _this.Indicator.FalseImage = DisplayGlobals.IndicatorsSpecial["BlankSmall"];
                         jQuery(this).addClass("active"); 
                     }(i,j)
               );
               div.appendChild(img);   
          }
     }
}
for(DisplayGlobals.Indicators中的变量i)
{
var div=d.createElement(“div”);
div.style.width=“100%”;
运输署助理署长(分区);
对于(var j=0;j 0)
{   
var img=d.createElement(“img”);
jQuery(img).attr({
src:DisplayGlobals.Indicators[i][j],
阿尔特:我,
类名:“指示法师”
}).点击(
函数(indGroup,indValue){
jQuery(“.indicationMage”).removeClass(“活动”);
_this.Indicator.TrueImage=DisplayGlobals.Indicators[indGroup][indValue];
_this.Indicator.FalseImage=DisplayGlobals.IndicatorsSpecial[“BlankSmall”];
jQuery(this).addClass(“活动”);
}(i,j)
);
儿童分部(img);
}
}
}
我尝试了几种不同的方法,但都没有成功


最初的问题是_this.Indicator.TrueImage始终是最后一个值,因为我使用循环计数器而不是参数来选择正确的图像。

您缺少一个函数。.click函数需要一个函数作为参数,因此需要执行以下操作:

.click(
    function(indGroup,indValue)
    {
        return function()
        {
            jQuery(".IndicatorImage").removeClass("active");
            _this.Indicator.TrueImage = DisplayGlobals.Indicators[indGroup][indValue];
            _this.Indicator.FalseImage = DisplayGlobals.IndicatorsSpecial["BlankSmall"];
            jQuery(this).addClass("active"); 
        }
    }(i,j);
);

通过Greg实现的解决方案仍然有效,但是您可以使用jQuery方法(或任何其他事件绑定方法)的
eventData
参数,而无需创建额外的闭包

看起来更简单,可能更有效(每次迭代少一个闭包)


方法的文档中有关于事件数据的描述和一些示例。

Nikita只要您使用jQuery 1.4.3及更高版本,其回答就可以了。对于此版本之前的版本(回到1.0),您必须使用,如下所示:

.bind('click', {indGroup: i, indValue : j}, function(event) {
    alert(event.data.indGroup);
    alert(event.data.indValue);
    ...
});
希望这能帮助其他仍在使用1.4.2的人(像我一样)

.bind('click', {indGroup: i, indValue : j}, function(event) {
    alert(event.data.indGroup);
    alert(event.data.indValue);
    ...
});