I really don´t know what is happening to me..
The code is like:
for (var j=0; j<tours.length; j++){
var name = tours[j].name;
var $tourLI = $('<li id="'+name+'"></li>');
var $tourButton = $('<div class="button-inside"><span>'+name+'</span><span></span></div>');
$tourButton.click(function() {
alert(name);
}
}
I´m trying to bind the click event for each button which displays the tours name, but is always displaying the last tour name whichever the button I’m clicking.
What am I doing wrong?
Thanks!
You need to wrap the click handler in a closure to ‘close-over’ the value of the variable
namebefore the for-loop moves on.This is because the handler isn’t actually executed until you click on it, so otherwise it will simply use the current value of
nameat that time (whatever the last value in the loop was).