簡體   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