jQuery闭包,循环和事件

我有一个类似于这里的问题: 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 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始终是最后一个值,因为我使用循环计数器而不是参数来选择正确的图像。

你错过了一个function。 .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 click方法的eventData参数(或绑定或任何其他事件绑定方法)来创建额外的闭包。

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

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

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

只要您使用的是jQuery 1.4.3及更高版本, Nikita的答案就可以正常运行。 对于之前的版本(返回1.0),您必须使用bind ,如下所示:

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

希望这可以帮助其他人仍然使用1.4.2(像我一样)