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

后端 未结 22 1406
旧巷少年郎
旧巷少年郎 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:23

    Inline Alternative:

    <div>
        <!-- Other content. -->
        <a onclick='event.stopPropagation();' href="http://foo.com">I don't want #clickable to handle this click event.</a>
    </div>
    
    0 讨论(0)
  • 2020-11-22 01:26

    Using return false; or e.stopPropogation(); will not allow further code to execute. It will stop flow at this point itself.

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

    You need to stop the event from reaching (bubbling to) the parent (the div). See the part about bubbling here, and jQuery-specific API info here.

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

    If it is in inline context, in HTML try this:

    onclick="functionCall();event.stopPropagation();
    
    0 讨论(0)
  • 2020-11-22 01:29

    Writing if anyone needs (worked for me):

    event.stopImmediatePropagation()
    

    From this solution.

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

    You can check whether the target is not your div-element and then issue another click event on the parent after which you will "return" from the handle.

    $('clickable').click(function (event) {
        let div = $(event.target);
        if (! div.is('div')) {
           div.parent().click();
           return;
        }
        // Then Implement your logic here
    }
    
    0 讨论(0)
提交回复
热议问题