表事件委托中所有按钮的JavaScript事件监听器?

问题描述 投票:0回答:3

我一直在使用oneclick方法,并且正在重写我的网站,并希望切换到现代的服务器(事件侦听器)

我了解如何添加事件监听器。


Const button = document.getElementById('button'); 

button.addEventListener('click');

我可以遍历所有按钮,但是如何正确地进行事件委托?

基本上我有一张桌子。我想将其中具有特定类“编辑用户”的每个按钮作为目标,并监听所有被单击的按钮。

谢谢,但是在最佳方式上委托事件并指定特定元素并为整个表使用一个事件侦听器感到困惑。为每个按钮添加50个不同的侦听器似乎很糟糕。

javascript event-listener
3个回答
0
投票

事件委托以这种方式工作:

<table id="my-table">

 ...

  <tr>
    <td>
      <button class="edit-user">aaa</button>
 ...

  <tr>
    <td>
      <button class="edit-user">bbb</button>
 ...

  <tr>
    <td>
      <button class="other-class">ccc</button>
 ...
const myTable = document.querySelector('#my-table')

myTable.onclick = e =>
  {
  if (!e.target.matches('button.edit-user')) return // reject other buttons

  console.log( e.target.textContent)  // show "aaa" or "bbb"

  // ...
  }

0
投票

这里是一个示例,请注意,您可以动态添加新按钮,并且仍然可以通过向每个元素添加事件侦听器来实现的方式工作,因此在我的示例中,有一个按钮"add more buttons"可以动态添加更多按钮演示所有可点击方式都相同。

var butCont = document.querySelector("#buttons-container");
butCont.onclick = function(e) {
  if(e.target.nodeName === "BUTTON") {
    //to prevent hiding the snippet with the console
    console.clear();
    console.log(e.target.textContent);
  }
};

for(var i = 0;i < 50; i++) {
  butCont.innerHTML += `<button>${i + 1}</button>`;
}

//don't worry the .querySelector will get the first button which is the add more buttons one and not other button
document.querySelector("button").onclick = function() {
  butCont.innerHTML += `<button>${i += 1}</button>`;
}
#buttons-container {
  width: 300px;
}
button {
  width: 30px;
  height: 30px;
}
<button style="width: 300px;">add more buttons</button>
<div id="buttons-container">
</div>

-1
投票

Try forEach()循环将侦听器添加到按钮中的每个按钮。我知道这仍然是每个事件的事件侦听器,但是代码更少。

或者您有

let buttons = document.querySelectorAll('.popupbutton')
© www.soinside.com 2019 - 2024. All rights reserved.