Skip to content Skip to sidebar Skip to footer

Assign Click Handler In For Loop In Javascript

Can anyone tell me why this works: $('#test1 td').click(function(event) { $('#test1').addClass('tableRowSelected'); }); $('#test2 td').click(function(event) { $('#test2').addCl

Solution 1:

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.

Solution 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

Solution 3:

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.

Post a Comment for "Assign Click Handler In For Loop In Javascript"