繁体   English   中英

防止在单击子下拉菜单时触发父元素单击事件

[英]Prevent parent element click-event to trigger when child-dropdown clicked

  • 我有一个可点击的父元素。 作为一个子元素,我有一个下拉菜单。 当我单击此下拉菜单时,它还会触发父元素。
  • 表格元素动态呈现为行,因此我想通过 Id 而不是 class 来定位元素。
  • 我尝试过使用 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>

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

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");
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM