2

all I made some of testing code that looks like this.

var selects = [$('#elem1'), $('#elem2'), $('#elem3')];

$.each(selects, function(item){
    selects[item].bind('click', function(){
        console.log("each function : " + item);
    });
});

for(var i = 0; i < selects.length; i++){
    var elem = selects[i];
    elem.bind('click', function(e){
        console.log("for loop : " + i);
    });
}

I made three buttons to be bound to event. and tested

If I click the button identified by name 'elem1', the result is :

console $
each function : 0
for loop : 3

and also If I click the button identified by name 'elem2', the result is :

console $
each function : 1
for loop : 3

What happened between two loop example? Please let me know.

Thank you, have a nice day.

Scalalang2
  • 536
  • 1
  • 7
  • 19
  • 1
    you can search `javascript closure` in google for how and why. – pktangyue Mar 19 '13 at 02:27
  • Search SO for [`javascript loop last value`](http://stackoverflow.com/search?q=javascript+loop+last+value). There are [too] many duplicates. Once you find a suitable duplicate, please mark this question appropriately. –  Mar 19 '13 at 02:30
  • http://stackoverflow.com/questions/6425062/passing-functions-to-settimeout-in-a-loop-always-the-last-value , http://stackoverflow.com/questions/2520587/variable-in-javascript-callback-functions-always-gets-last-value-in-loop , http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example , etc –  Mar 19 '13 at 02:32
  • Thanks, I didn't hear what closure is. I'll check. and I am happy to understand this! Thanks pktangyue, pst, and Blender – Scalalang2 Mar 19 '13 at 04:09

1 Answers1

0

i refers to the counter variable itself, not the value of it. You have to pass it by value:

for(var i = 0; i < selects.length; i++){
    var elem = selects[i];

    (function(i) {
        elem.bind('click', function(e) {
            console.log("for loop : " + i);
        });
    })(i);
}

Shadowing i in an anonymous function does that.

Blender
  • 289,723
  • 53
  • 439
  • 496