I am trying to make each tr of a big table to toggle a div inside one of its td’s on click, here is what I’ve done:
for( i = 2 ; i < trLen; i++ ){
var id = $("td.idout", "tr:eq(" + i + ")").text();
$("tr:has(div#" + id + ")").click(function(){
$("div #"+ id).toggle();
});
}
I have each of the div’s id’s made the same as the entry (which is output in the selection referred by the var id above). I’ve tested each selection and they are all perfect. There must be something wrong with my logic because it just won’t work. It doesn’t do anything at all.
The
varkeyword declares function-scoped variables, opposed to block-scoped that you might’ve expected. So, you only have 1idthat’s shared by each iteration of theforloop. And, since theclickfunction will be called after the loop has finished,idwill always have the last value from the loop for this selector:You can fix this with an immediately-invoked function, which will enclose the variable for each iteration:
Or, eventually, you’ll be able to use the
letkeyword instead: