Assign click handler in for loop in Javascript

2019-07-23 10:42发布

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 :(

3条回答
Explosion°爆炸
2楼-- · 2019-07-23 11:19

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.

查看更多
Melony?
3楼-- · 2019-07-23 11:20

UPDATE

To get it to work, change $("#test" + i).addClass("tableRowSelected"); to $(this).parents('tr').addClass("tableRowSelected");

As Pointy pointed out, actually i does exist with a value of 4 which is invalid.


That's because, in the second case, when the event actually gets fired, i no longer exists.

查看更多
一纸荒年 Trace。
4楼-- · 2019-07-23 11:27

What about using:

$("table").on("click", "td", function() {
    $(this).parent().addClass("tableRowSelected");
});

This will use event delegation to attach the event to the table and filter click events by td

查看更多
登录 后发表回答