我试图让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);
};
答案 0 :(得分:3)
classname
是NodeList
,addEventListener
是单个节点的方法。你需要遍历元素:
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';
});
}):