JavaScript click handler not working as expected inside a for loop [duplicate]

Working DEMO

This is a classic JavaScript closure problem. Reference to the i object is being stored in the click handler closure, rather than the actual value of i.

Every single click handler will refer to the same object because there’s only one counter object which holds 6 so you get six on each click.

The workaround is to wrap this in an anonymous function and pass i as argument. Primitives are copied by value in function calls.

for(var i=1; i<6; i++) {
     (function (i) {
        $("#div" + i).click(
            function () { alert(i); }
        );
     })(i);
}

UPDATE

Updated DEMO

Or you can use ‘let’ instead var to declare i. let gives you fresh binding each time. It can only be used in ECMAScript 6 strict mode.

'use strict';

for(let i=1; i<6; i++) {

        $("#div" + i).click(
            function () { alert(i); }
        );
 }

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)