2

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
ingh.am
  • 25,981
  • 43
  • 130
  • 177
  • 1
    possible duplicate of [Assign click handlers in for loop](http://stackoverflow.com/questions/4091765/assign-click-handlers-in-for-loop) – T.J. Crowder Jan 16 '12 at 14:26
  • Sorry - I didn't see that, I think that answer is good for me though thanks. – ingh.am Jan 16 '12 at 14:26

3 Answers3

2

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.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • This place will get kind-of lonely once some genius builds smarts into a popular IDE to explain this to people. – Pointy Jan 16 '12 at 14:25
  • The answer to http://stackoverflow.com/questions/4091765/assign-click-handlers-in-for-loop you suggested did it thanks. – ingh.am Jan 16 '12 at 14:44
  • @ing0: Good deal. I think I'll add an explanation to that answer at some point, it's pretty lacking at present but that title seems like it should come up on searches a lot. – T.J. Crowder Jan 16 '12 at 15:09
  • I checked a few answers but didn't see that one. I think I foolishly thought it was something not-so common. Thanks again. – ingh.am Jan 16 '12 at 16:19
2

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

danwellman
  • 9,068
  • 8
  • 60
  • 88
-1

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.

techfoobar
  • 65,616
  • 14
  • 114
  • 135