JavaScript table 事件委托中所有按钮的事件侦听器?

JavaScript event listener for all buttons in table Event Delegation?

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

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


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

button.addEventListener('click');

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

基本上我有一个table。我想定位其中具有特定 class“edit-user”的每个按钮,并监听任何被点击的按钮。

谢谢,但充其量只能混淆事件委托和目标特定元素的最佳方式,并为整个 table 设置一个事件侦听器。为每个按钮添加 50 个不同的侦听器似乎很糟糕。

这是一个示例,请注意,您可以动态添加新按钮,并且它仍然可以在向每个元素添加事件侦听器时无法实现,因此在我的示例中有一个按钮 "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>

事件委托是这样工作的:
(使用 element.matches 更容易)

<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"

  // ...
  }