JS error object has no method addEventListener

后端 未结 2 1134
梦谈多话
梦谈多话 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:40

    Because, exactly as the error message tells you NodeLists don't have an addEventListener method. You should iterate over the nodelist, and addEventListener to each element within – assuming that you want to add N listeners.

    Alternately, select only a single element, and the remainder of your code will work as written.

提交回复
热议问题