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.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.What about using:
This will use event delegation to attach the event to the table and filter click events by td