-1

If you try this code with "let i" it works, and with "var i" it doesn't work.

Can you explain me why?

$(document).ready(function () {
    for (let i=0; i<20; i++) {
        $('<button />').append(i).appendTo('body').click(function() {
            console.log(i);
        });
    }
});
Olivier Pons
  • 15,363
  • 26
  • 117
  • 213

2 Answers2

1

var will declare it in the scope of the anonymous function passed to the ready method, meaning there can be only be one i in the anonymous function scope hence you are getting this issue, the last number that was updated for i is shown!. When you define with let its scope is limited to the block on which its defined, which is the for loop, hence it works fine. Hope this helps you!

For further info visit here

$(document).ready(function () {
    for (let i=0; i<20; i++) {
        $('<button />').append(i).appendTo('body').click(function() {
            console.log(i);
        });
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Naren Murali
  • 19,250
  • 3
  • 27
  • 54
  • "var will define the variable in the global scope" — No, it won't. It will declare it in the scope of the anonymous function passed to the `ready` method. – Quentin Feb 07 '19 at 10:10
  • @Quentin I understand now, `var` is function scoped, should have noted this, didn't notice the ready function though, have edited my answer! – Naren Murali Feb 07 '19 at 10:22
-1

have you tried to use .on('click', function(){}) ?

$(document).ready(function () {
    for (let i=0; i<20; i++) {
        let button = $('<button />').append(i);
        button.appendTo('body');
        button.on('click', function() {
            console.log(i);
        });
    }
});

i think the button first have to be existing before assinging click action listener

mtizziani
  • 956
  • 10
  • 23