1

I'm working with JavaScript and jQuery and I want to display a bunch of buttons.

These buttons get a name from a variable incremented in the loop and they should show this number.

The naming process works fine, but when I click on these buttons I get everytime the value 10. I know the reason for this output, but I don't know how I can get the real number of the button (I don't want to get the value from the button name). Is there a way to make the 'click' value 'static' ?

Here is a example code :

<script>
for(var i = 0; i < 10; i++) {
  $(document.createElement('button'))
    .html(i)
    .click(function() {
        alert(i);
    })
    .appendTo($(document.body));
}
</script>
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
rpanske
  • 125
  • 1
  • 2
  • 10

2 Answers2

2

That because the click event will be attached in every iteration, to avoid that you could give them a common class (common for example) then attach the click to this class like :

for(var i = 0; i < 10; i++) {
  $(document.createElement('button'))
    .addClass('common')
    .html(i)
    .appendTo($(document.body));
}


$('body').on('click', '.common', function(e) {
  console.log( $(this).text() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
2

You can achieve that by the following two ways:

  1. Simply using ES6's let instead of var inside for loop.

for(let i = 0; i < 10; i++) {
  $(document.createElement('button'))
    .html(i)
    .click(function() {
        alert(i);
    })
    .appendTo($(document.body));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  1. By using IIFE (Immediately Invokable Function Expression) inside for loop like the following:

for(var i = 0; i < 10; i++) {
  (function(j){$(document.createElement('button'))
    .html(j)
    .click(function() {
        alert(j);
    })
    .appendTo($(document.body));
  })(i);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Mamun
  • 66,969
  • 9
  • 47
  • 59