javascript - Why does the alert coming from my loop always return the last value, not each iteration value? -


this question has answer here:

i have buttons, stored in array. loop through array add click event each button. each click alerts value of i. expect values 1, 2, 3 , on, come 1 value, in case 3.

can explain why happens , how fix it?

please see a jsfiddle. code below:

var thebuttons = ['.button.one', '.button.two', '.button.three'];  (i=0; i<thebuttons.length; i++) {     $(thebuttons[i]).click(function () {         alert(i); // returns 3     }); } 

please explain , can - i'm of beginner @ javascript , programming.

by time click on button i === 3. need pass value of i closure:

for (var = 0; i<thebuttons.length; i++) { // `var i` not global     (function(index){         $(thebuttons[i]).on('click', function () {            alert(index); // index === value passed         });     })(i); // pass value of } 

fiddle demo: http://jsfiddle.net/maniator/fe55y/3/


Comments