Rob*_*ett 9 javascript jquery closures loops
我有一个类似于这里的问题: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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试了几种不同的方法但没有成功......
最初的问题是_this.Indicator.TrueImage始终是最后一个值,因为我使用循环计数器而不是参数来选择正确的图像.
Gre*_*reg 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);
);
Run Code Online (Sandbox Code Playgroud)
Nik*_*bak 13
Greg的解决方案仍然有效,但您现在可以通过利用eventDatajQuery click方法的参数(或绑定或任何其他事件绑定方法)来创建额外的闭包.
.click({indGroup: i, indValue : j}, function(event) {
alert(event.data.indGroup);
alert(event.data.indValue);
...
});
Run Code Online (Sandbox Code Playgroud)
看起来更简单,可能更有效(每次迭代少一次闭包).
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);
...
});
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助其他人仍然使用1.4.2(像我一样)
| 归档时间: |
|
| 查看次数: |
7237 次 |
| 最近记录: |