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

I’m trying to learn JS and got an issue.

I tried many things and googled but all in vain. Following piece of code doesn’t work as expected. I should get value of i on click but it always returns 6. I’m pulling my hair out; please help.

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

    console.log(i);

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

jsfiddle

3 Answers
3

Leave a Comment