【问题标题】:JavaScript event listener for all buttons in table Event Delegation?表事件委托中所有按钮的JavaScript事件侦听器?
【发布时间】:2020-08-27 17:08:43
【问题描述】:

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

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


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

button.addEventListener('click');

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

基本上我有一张桌子。我想定位其中具有特定类“编辑用户”的每个按钮,并监听任何被点击的按钮。

谢谢,但是对于事件委托和定位特定元素以及为整个表设置一个事件侦听器的最佳方式感到困惑。为每个按钮添加 50 个不同的侦听器似乎很糟糕。

【问题讨论】:

  • 事件委托仅适用于 DOM 的分层上下文(父元素到子元素)

标签: javascript event-listener


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    事件委托以这种方式工作:
    (使用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"
    
      // ...
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多