How do I prevent a parent's onclick event from firing when a child anchor is clicked?

后端 未结 22 1407
旧巷少年郎
旧巷少年郎 2020-11-22 00:37

I\'m currently using jQuery to make a div clickable and in this div I also have anchors. The problem I\'m running into is that when I click on an anchor both click events ar

相关标签:
22条回答
  • 2020-11-22 01:29

    ignoreParent() is a pure JavaScript solution.

    It works as an intermediary layer that compares the coordinates of the mouse click with the coordinates of the child element/s. Two simple implementation steps:

    1. Put the ignoreParent() code on your page.

    2. Instead of the parent's original onclick="parentEvent();", write:

    onclick="ignoreParent(['parentEvent()', 'child-ID']);"
    

    You may pass IDs of any number of child elements to the function, and exclude others.

    If you clicked on one of the child elements, the parent event doesn't fire. If you clicked on parent, but not on any of the child elements [provided as arguments], the parent event is fired.

    ignoreParent() code on Github

    0 讨论(0)
  • 2020-11-22 01:30

    If you do not intend to interact with the inner element/s in any case, then a CSS solution might be useful for you.

    Just set the inner element/s to pointer-events: none

    in your case:

    .clickable > a {
        pointer-events: none;
    }
    

    or to target all inner elements generally:

    .clickable * {
        pointer-events: none;
    }
    

    This easy hack saved me a lot of time while developing with ReactJS

    Browser support could be found here: http://caniuse.com/#feat=pointer-events

    0 讨论(0)
  • 2020-11-22 01:31

    Here my solution for everyone out there looking for a non-jQuery code (pure javascript)

    document.getElementById("clickable").addEventListener("click", function( e ){
        e = window.event || e; 
        if(this === e.target) {
            // put your code here
        }
    });
    

    Your code wont be executed if clicked on parent's childs

    0 讨论(0)
  • 2020-11-22 01:31

    you can also try this

    $("#clickable").click(function(event) {
       var senderElementName = event.target.tagName.toLowerCase();
       if(senderElementName === 'div')
       {
           // do something here 
       } 
       else
       {
          //do something with <a> tag
       }
    });
    
    0 讨论(0)
提交回复
热议问题