JS error object has no method addEventListener

后端 未结 2 1137
梦谈多话
梦谈多话 2020-12-10 21:22

I have following code

var el = document.querySelectorAll(\'.block\');
console.log(el);
el.addEventListener(\'click\', function () {
    alert(\'hello\');
},          


        
2条回答
  •  独厮守ぢ
    2020-12-10 21:57

    The method querySelectorAll() returns a NodeList which is a collection of nodes.

    Hence you need to iterate it to attach event listeners

    var el = document.querySelectorAll('.block');
    for(var i=0; i < el.length; i++){
        el[i].addEventListener('click', function () {
            alert('hello');
        }, false);
    }
    

提交回复
热议问题