JS error object has no method addEventListener

后端 未结 2 1135
梦谈多话
梦谈多话 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.

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
提交回复
热议问题