0

JSFiddle

var arr = [ [0], [1], [2], [3] ];
for ( var i = 0; i < arr.length; i++ ) {
    $('#btn-' + i).click(function() {
        console.log(i);
    });    
}

When I'm clicking on corresponding button console.log always shows me last iteration instead of the current iteration. Why?

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
user3724896
  • 139
  • 2
  • 12
  • 1
    Ditch it all and use this: $("[id^='btn-']").click(function(event){alert($(this).index());}); http://jsfiddle.net/m6Lbdpxm/ – Moob Oct 01 '14 at 10:42

2 Answers2

2

Try creating a closure, In other words, create a scope per iteration. Now in your code all the event handlers are created in a single scope and the i inside of that scope would get updated instantly to 4. So as a result, when you clicking on all the buttons the result would be same. That is the updated one of i

for ( var i = 0; i < arr.length; i++ ) {

    var j = function(x) {
      $('#btn-' + x).click(function() {
        console.log(x);
      });
    }

    j(i);    
}

DEMO

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
1

Because of closure! For that you can do this:

for (var i = 0; i < arr.length; i++) {
    (function(n) {
        $('#btn-' + i).click(function() {
            console.log(n);
        });
    })(i);
}

DEMO

Amit Joki
  • 58,320
  • 7
  • 77
  • 95