-1

I'm curious why when clicking on each input checkbox all the alerts are "_3" when I'm expecting "_0", "_1" and "_2" respectively. How would I go about getting the results I expect without much modification. This is to solve a much larger problem in a project I'm working on.

<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <div id="main"></div>
    <script>

    var generate = function() 
    {
        var elem = document.getElementById('main');
        var list = document.createElement('ul');

        for(var i=0; i<3;i++)
        {
            var liElem = document.createElement('li');
            var x = document.createElement('input');
            x.setAttribute('type', 'checkbox');
            x.setAttribute('value', i);
            x.setAttribute('id', '_A' + i);
            x.addEventListener('change', function () { alert('_'+(i)); });
            liElem.appendChild(x);
            list.appendChild(liElem);
        }
        elem.appendChild(list);
    }

    window.addEventListener('load', function () {
        generate();
    });

    </script>
</body>
</html>

EDIT: found this as solution

x.addEventListener('change', function (i) { console.log('_'+i); }.bind(this, i));'
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

0

You could use this.id which gives you the element's id in event's context:

var generate = function() {
  var elem = document.getElementById('main');
  var list = document.createElement('ul');

  for (var i = 0; i < 3; i++) {
    var liElem = document.createElement('li');
    var x = document.createElement('input');
    x.setAttribute('type', 'checkbox');
    x.setAttribute('value', i);
    x.setAttribute('id', '_A' + i);
    x.addEventListener('change', function() {
      console.log('_' + this.id.slice(-1));
    });
    liElem.appendChild(x);
    list.appendChild(liElem);
  }
  elem.appendChild(list);
}

window.addEventListener('load', function() {
  generate();
});
<div id="main"></div>
shrys
  • 5,860
  • 2
  • 21
  • 36
  • 1
    Not a fan of the id solution but did find this which works well x.addEventListener('change', function (component) { console.log('_'+i); }.bind(this, i)); – Ian Knowles Jul 29 '19 at 14:33