How to add one event listener for all buttons

前端 未结 4 1933
孤城傲影
孤城傲影 2020-12-19 12:02

How do I add an event listener to multiple buttons and get the value of each one depending on the one clicked. Eg:

4条回答
  •  萌比男神i
    2020-12-19 12:14

    You don't really need to add listeners to all the buttons. There is such thing in JS as Bubbling and capturing so you can wrap all your buttons with a div and catch all the events there. But make sure you check that the click was on a button and not on the div.

    const wrapper = document.getElementById('wrapper');
    
    wrapper.addEventListener('click', (event) => {
      const isButton = event.target.nodeName === 'BUTTON';
      if (!isButton) {
        return;
      }
    
      console.dir(event.target.id);
    })
    div {
      padding: 20px;
      border: 1px solid black;
    }

提交回复
热议问题