如何为所有按钮添加一个事件侦听器 [英] How to add one event listener for all buttons

查看:54
本文介绍了如何为所有按钮添加一个事件侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将事件侦听器添加到多个按钮,并根据单击的按钮获得每个按钮的值.例如:

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>

因此在javascript上,我不必引用每个按钮,例如:

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

Const but1 = document.getElementById('but1'); 
but1.addEventListener('click');

推荐答案

您实际上不需要将侦听器添加到所有按钮.JS中有冒泡和捕获这样的东西,因此您可以包装所有 buttons div 并捕获那里的所有事件.但是请确保您检查单击是否在按钮上,而不是在 div 上.

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>

这篇关于如何为所有按钮添加一个事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆