简体   繁体   中英

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

  • I have a clickable parent element. As a child element I have a dropdown. When I click this dropdown, it also triggers the parent element.
  • The table elements are rendered dynamically as rows, thus I would like to target the elements by Id and not by class.
  • I have tried with e.stopPropagation() but then it prevents the dropdown to toggle.
  • Very thankful for any help!

 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>

You could return early in your parent listener callback if the event target is the dropdown.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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