Concise event listeners on array elements

前端 未结 2 2015
我在风中等你
我在风中等你 2021-01-23 14:01

I was wondering if there is a more concise way to perform this same action.

I\'m trying to listen for events on two separate buttons that perform the same action, and bo

相关标签:
2条回答
  • 2021-01-23 14:38

    I am not sure that one event handler is good. It could be if you are adding 100s of events. If it is a few, that you can easily just use a loop to add them.

    const returnButtons = document.querySelectorAll('.return');
    
    function test () {
      console.log(this.textContent) //can use this
    }
    
    returnButtons.forEach( function (btn) {
      btn.addEventListener("click", test)
    })
    <button class="return">One</button>
    <button class="return">Two</button>

    0 讨论(0)
  • 2021-01-23 14:46

    If you just want to have a single call to addEventListener then you can use event delegation by setting the event listener on a common parent element. For instance you could set it on document. You would then get which button that was clicked from the target property from the event object that is automatically passed to event listeners

    document.addEventListener('click',event=>{
      var button = event.target;
      //check that the element click was one of the 'return' buttons
      if(button.classList.contains('return')){
        returnToMainContent(button);
      }
    });
    
    function returnToMainContent(button){
        button.parentElement.style.display = "none";
        mainContent.style.display = "block";
    }
    
    0 讨论(0)
提交回复
热议问题