for循环后将addEventListener添加到类中;香草JS

时间:2015-04-21 15:21:54

标签: javascript for-loop addeventlistener

我试图让eventlistener为循环中创建的类工作。我无法使用它,有什么建议吗?

window.onload = function(){
  var div = document.createElement('div'),
    container = document.getElementById('container'),
    classname = document.getElementsByClassName("hello");

  div.className = 'hello';

  var tasks = [
    'One',
    'Two',
    'Three',
    'Four'
  ];

  for (var i = 0; i < tasks.length; ++i) {
    container.innerHTML += '<div class="hello"><p>' + tasks[i] + '</p></div>';
  }

  classname.addEventListener('click', function(){
    this.className = 'done';
  });

  console.log(classname);
};

2 个答案:

答案 0 :(得分:3)

classnameNodeListaddEventListener是单个节点的方法。你需要遍历元素:

for (i = 0; i < classname.length; i++) {
    classname[i].addEventListener('click', function() {
        this.className = 'done';
    }
}

答案 1 :(得分:1)

getElementsByClassName返回一个NodeList,因此您无法在其上添加事件侦听器。您必须要将事件侦听器添加到此列表中的元素。

所以这给了:

//NodeList has not forEach method, but we can take it from an array
[].forEach.call( classnameElements, function( classnameElement ){
  classnameElement.addEventListener('click', function(){
    this.className = 'done';
  });
}):