Javascript - array element undefined when adding eventlistener

I am new to javascript and I am trying to capture all the "td" elements in the DOM and add a click event to them. When the code finishes executing, I can see that I have 37 elements in an array of cells, but when I click on an element, I get "clicked td37 undefined" in my console instruction no matter which element is clicked. I do not know what is wrong and any help would be appreciated.

<script>
window.addEventListener("DOMContentLoaded", createEventListeners, false);

function createEventListeners() {
   var cells = document.getElementsByTagName("td");
   console.log(cells);

   for (var i = 0; i < cells.length; i++) {
      cells[i].addEventListener("click", function () {
      console.log("clicked td" +  i + " " + cells[i]);

      }, false);
   }

 }
</script>
+4
source share
4 answers

i cells.length, cells[i] - undefined. , i - , .

function createEventListeners() {
  var cells = document.getElementsByTagName("td");

  for (var i = 0; i < cells.length; i++) {
    (function(i) {
      cells[i].addEventListener("click", function () {
        console.log("clicked td" +  i + " " + cells[i]);
      }, false);
    }(i));
}
+3

. . Event i , , , . :

var pre = onload; // previous onload
onload = function(){
  if(pre)pre();
  function createEventListeners(){
    var cells = document.getElementsByTagName('td');
    for(var i=0,l=cells.length; i<l; i++){
      (function(i){
        cells[i].addEventListener('click', function(){
          console.log('i is at position:'+i));
        }, false);
      })(i);
    }
  }
  window.addEventListener('DOMContentLoaded', createEventListeners, false);
}
+3

i , , , . , 10 , 0-9, i 10.

0

+ - , . jQuery, each jQuery. each, , , :

$(document).ready(function () {
    var $tds = $('td');
    $tds.each(function (i, td) {
        $(td).click(function () {
            console.log(i, td);
        });
    });
});

. , , , i :

window.addEventListener("DOMContentLoaded", createEventListeners, false);
function createEventListeners() {
    var cells = document.getElementsByTagName("td");
    console.log(cells);

    for (var i = 0; i < cells.length; i++) {
        cells[i].setAttribute('data-i', i);
        cells[i].addEventListener("click", function () {
            var i = this.getAttribute('data-i');
            console.log("clicked td" + i + " " + cells[i]);

        }, false);
    }
}
0

Source: https://habr.com/ru/post/1616661/


All Articles