I insert elements to the DOM, after that I want to bind a click function to these elements.
This works, but for some reason the links that were created all return the same value, which
is the highest value ‘px_amount’ has after looping. Very strange 🙂 The first console.log();
does return the right value, and I can see it increment after each iteration. I added a simple console.log() to the click function, for sake of simplicity.
for(var i=1; i<=bullet_amount; i++)
{
$('<a id="bullet-'+i+'">'+i+' </a>').appendTo('#bullet-nav');
px_amount = (i-1)*ratio*3450;
console.log(px_amount);
$("#bullet-"+i).live('click', function() {
console.log(px_amount);
});
}
You should use a closure to capture the value of
ireather than the reference: