在Javascript中为for循环分配点击处理程序 [英] Assign click handler in for loop in Javascript

查看:86
本文介绍了在Javascript中为for循环分配点击处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

  $(#test1 td)。click(function(event) {
$(#test1)。addClass(tableRowSelected);
});
$(#test2 td)。click(function(event){
$(#test2)。addClass(tableRowSelected);
});

但这不是:

<$ p (函数(事件){$($))$($#$> $ $ $ $ b $ b $(#test+ i).addClass(tableRowSelected);
});
}

我也尝试过使用 i.toString( )在第二个代码片段中,但这没有帮助:($ / b>

解决方案

事件处理函数会收到 i 变量的持久引用,而不是其创建时的副本。请参阅其他答案以获取详细信息。


Can anyone tell me why this works:

$("#test1 td").click(function(event) {
  $("#test1").addClass("tableRowSelected");
});
$("#test2 td").click(function(event) {
  $("#test2").addClass("tableRowSelected");
});

But this doesn't:

for(var i = 1; i < 3; i++) {
  $("#test" + i + " td").click(function(event) {
    $("#test" + i).addClass("tableRowSelected");
  });
}

I've also tried using i.toString() in the second code snippet but this doesn't help :(

解决方案

The event handler function receives an enduring reference to the i variable, not a copy of it as of when it was created. See this other answer for details.

这篇关于在Javascript中为for循环分配点击处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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