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

后端 未结 3 1486
野的像风
野的像风 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:15

    Look at the documentation for querySelector:

    querySelector() returns the first Element within the document that matches the specified selector, or group of selectors.

    If you want to match more than one element, you'll need to use querySelectorAll and, because it doesn't return a single element loop over the result.

    Alternatively, you could use event delegation.

    0 讨论(0)
  • 2020-12-21 04:30

    Need to use querySelectorAll instead of querySelector. And iterate over the list like this.

    const breakdownButton = document.querySelectorAll('.breakdown');
    
    // It add event listeners for the first button element. 
    // you can use forloop or using map function to iterate for the list elements and here i used breakdownButton[0] as an example.
    
    breakdownButton[0].addEventListener('click', function() {
      console.log(this.innerHTML);
    });
    

    Use iterate functions like forEach or map. I used forEach

    const breakdownButton = document.querySelectorAll('.breakdown');
    breakdownButton.forEach(function(btn) {
      btn.addEventListener('click', function() {
        console.log();
      });
    });
    
    0 讨论(0)
  • 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);
      });
       });
    <button id='btn-1' type="button" name="first" class="breakdown main-text"> Breakdown Start </button>
    <button id='btn-2' type="button" name="second" class="breakdown main-text" disabled> Repair Start </button>
    <button id='btn-3' type="button" name="third" class="breakdown main-text" disabled> Repair End </button>
    <button id='btn-4' type="button" name="fourth" class="breakdown main-text" disabled> Breakdown Ended </button>

    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

    0 讨论(0)
提交回复
热议问题