Concise event listeners on array elements

前端 未结 2 2016
我在风中等你
我在风中等你 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: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";
    }
    

提交回复
热议问题