jQuery闭包,循环和事件 [英] jQuery Closures, Loops and Events

查看:90
本文介绍了jQuery闭包,循环和事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似这里的问题: JavaScript循环中的事件处理程序 - 需要一个闭包?但我使用的是jQuery,并且给出的解决方案似乎在绑定而不是点击时触发事件。

I have a question similar to the one here: Event handlers inside a Javascript loop - need a closure? but I'm using jQuery and the solution given seems to fire the event when it's bound rather than on click.

这里是我的代码:

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);   
          }
     }
}

不同的方式没有成功...

I've tried a couple of different ways without success...

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

The original problem was that _this.Indicator.TrueImage was always the last value because I was using the loop counters rather than parameters to choose the right image.

推荐答案

您缺少一个函数。 .click函数需要一个函数作为参数,因此您需要这样做:

You're missing a function. The .click function needs a function as a parameter so you need to do this:

.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);
);

这篇关于jQuery闭包,循环和事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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