Want to add “addEventListener” on multiple elements with same class

后端 未结 3 1507
野的像风
野的像风 2020-12-21 03:38

I\'d like to perform the logic in the \"onClick\" through the event listener in jS but it only seems to run once? I have the class in all four but I can\'t figure out why it

3条回答
  •  醉酒成梦
    2020-12-21 04:38

    You need to use querySelectorAll which will return a collection.Now use spread operator (three dots) to convert it to array and use forEach .Inside forEach callback add the event listener to it

    [...document.querySelectorAll('.breakdown')].forEach(function(item) {
      item.addEventListener('click', function() {
        console.log(item.innerHTML);
      });
       });
    
    
    
    

    In your snippet you have also attached inline event handler,that may not be necessary.

    If the objective is to enable the next button then a function to enable it can be called from the callback function of the event handler

提交回复
热议问题