Click event in parent and child

I have a parent div that has child div elements. I have separate click implementations for the parent and its children.

<div id="mainContainer">

    <div id="childContainer">    
    </div>

     <div id="childContainer2"> 
    </div>

</div>

$('#mainContainer').click(function () {

        console.log('main container');

    }).children().click(function () {
        console.log('childen');
        return false;
    });

    $('#childContainer2').click(function () {

        console.log('child container 2');

    }); 

It works great. but if I click on the child, then the event will be executed twice, and that is how it should work. My question is: is there a way that I can explicitly record the event to the parent, which will not affect the children so that the children cannot double-click?

+4
source share
3 answers

yes, you can just change the event binding order and stop propagating use stopImmediatePropagation

view this fiddle

$('#childContainer2').click(function (e) {       
       alert('child container 2'); 
        e.stopImmediatePropagation()
     return false;
    }); 
$('#mainContainer').click(function () {
alert('main container');

    }).children().click(function (e) {
       alert('childen');
        return false;
    });
+5

event.stopPropagation:

children().click(function (e) {
    e.stopPropagation();
    console.log('childen');
    return false;
});

+2

Both return false;and event.stopPropagationstop the spread of the parent events.

Here is a demo script .

+2
source

All Articles