Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

javascript - How to add one event listener for all buttons

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

<button id='but1'>
Button1
</button>
<button id='but2'>
Button2
</button>
<button id='but3'>
Button3
</button>
<button id='but4'>
Button4
</button>

So that on javascript, I wouldn't have to reference each button like:

Const but1 = document.getElementById('but1'); 
but1.addEventListener('click');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}
<div id='wrapper'>
  <button id='but1'>
  Button1
  </button>
  <button id='but2'>
  Button2
  </button>
  <button id='but3'>
  Button3
  </button>
  <button id='but4'>
  Button4
  </button>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...