jQuery 闭包、循环和事件

9

我有一个类似于这里的问题:JavaScript循环内的事件处理程序 - 需要闭包吗?但我正在使用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);   
          }
     }
}

我尝试了几种不同的方法,但都没有成功...

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

3个回答

14

您缺少一个函数。.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);
);

13

Greg提供的解决方案仍然有效,但现在您可以利用jQuery click方法(或bind或任何其他事件绑定方法)的eventData参数来完成它,而不需要创建额外的闭包。

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

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

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


6

Nikita的答案在使用jQuery 1.4.3及更高版本时运行良好。对于此之前的版本(1.0及以下),您需要按照以下方式使用bind

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

希望这能帮助其他仍在使用1.4.2版本的人(就像我一样)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接