【问题标题】:Prevent parent element click-event to trigger when child-dropdown clicked防止在单击子下拉菜单时触发父元素单击事件
【发布时间】:2021-02-11 08:16:10
【问题描述】:
  • 我有一个可点击的父元素。作为一个子元素,我有一个下拉菜单。当我点击这个下拉菜单时,它也会触发父元素。
  • 表格元素动态呈现为行,因此我希望按 Id 而不是按类定位元素。
  • 我已尝试使用 e.stopPropagation(),但它会阻止下拉菜单切换。
  • 非常感谢您的帮助!

document.getElementById("entirerow"+doc.id).addEventListener("click", function(e){
  alert("Entire row clicked")
})

document.getElementById("dropdown"+doc.id).addEventListener("click", function(e){
  alert("Only button clicked")
  //e.stopPropagation(); I have tried this but it prevents the dropdown from triggering at all.
})
<tr id="entirerow"+doc.id>
  <td>
  <span>
    <button id="dropdown"+doc.id>myDropdown</button>
  </span>
  </td>
  <td>
    ...
  </td>
</tr>

【问题讨论】:

    标签: javascript firebase twitter-bootstrap dropdown


    【解决方案1】:

    如果事件目标是下拉列表,您可以在父侦听器回调中提前返回。

    document.getElementById("entirerow"+doc.id).addEventListener("click", function(e){
      if(e.target.id === ("dropdown"+doc.id)){
        return;
      }
    
      alert("Entire row clicked");
    })
    
    document.getElementById("dropdown"+doc.id).addEventListener("click", function(e){
      alert("Only button clicked");
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-02
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      • 2018-07-27
      • 1970-01-01
      相关资源
      最近更新 更多