Prevent nested elements from triggering an event for parent element

后端 未结 2 1644
时光取名叫无心
时光取名叫无心 2020-12-09 05:14

Structure:

.parent (has if/else to toggle on click) -> .child (has nothing)

Parent
相关标签:
2条回答
  • 2020-12-09 05:47

    Use event.stopPropagation();:

    $('#a').add('#b').click(fun1);
    
    function handler(event) {
        event.stopPropagation();
        // now do your stuff        
    }
    
    0 讨论(0)
  • 2020-12-09 06:08

    Solution 1: Compare target with currentTarget:

    $("#parentEle").click( function(e) {
        if(e.target == e.currentTarget) {
            alert('parent ele clicked');
        } else {
            //you could exclude this else block to have it do nothing within this listener
            alert('child ele clicked');
        }
    });
    

    Fiddle

    e.target will be the element that started the event.
    e.currentTarget will be where it currently is (bubbling up) which will be parentEle in this click event as that's what this is listening for.

    If they are the same, you know the click was directly on the parent.


    Solution 2: Stop the propagation before the event hits the parentEle:

    The other option is to prevent the event from bubbling up in the first place if there is a click on a child element. That can be done like this:

    $("#parentEle").click( function(e) {
        alert('parent ele clicked');
    });
    $("#parentEle").children().click( function(e) {
        //this prevent the event from bubbling to any event higher than the direct children
        e.stopPropagation();
    });
    

    Fiddle


    The main difference between the two is that the first solution will just ignore the event in this listener and allow it to keep bubbling up. This may be necessary if you have a parent of this parentEle that needs to get the event.

    The second solution stops any click events from bubbling past parentEle's direct children. So if there was a click event on a parent of parentEle, they would never see these events either.

    0 讨论(0)
提交回复
热议问题