代码之家  ›  专栏  ›  技术社区  ›  Rob Stevenson-Leggett

jquery闭包、循环和事件

  •  9
  • Rob Stevenson-Leggett  · 技术社区  · 16 年前

    我有一个类似的问题: Event handlers inside a Javascript loop - need a closure? 但我使用的是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 回复  |  直到 13 年前
        1
  •  14
  •   Greg    16 年前

    您缺少一个函数。.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);
    );
    
        2
  •  13
  •   Nikita Rybak    14 年前

    解决方案 格雷戈 仍然有效,但您可以通过使用 eventData jquery参数 click 方法(或) bind 或任何其他事件绑定方法)。

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

    看起来简单多了,而且效率可能更高(每次迭代少一个闭包)。

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

        3
  •  6
  •   Dave Oleksy    13 年前

    尼基塔 只要您使用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的人(像我一样)