I’m trying to work out a trivial issue:
var setListeners = function()
{
for(var i in sliders)
{
sliders[i].switchBtn.click(function()
{
alert(i);
});
}
}
There are three elements in sliders, so 3 switchBtn’s are given a click listener. I expected that clicking the first button would alert with a ‘0’, the second a ‘1’ and the third a ‘2’. However when I press each button, I just get ‘2’.
Could someone please point out why the value of i is overridden for each new listener function?
since i is outside of the function, you’re always referencing the same variable and it’s always 2. You need a closure to get this to work properly:
n (was i) is now bound in a closure and your alerts will show properly.