Prevent execution of parent event handler

2018-12-31 08:44发布

I have a tree of divs:

<div id="a" onclick="func">
    <div id="b" onclick="func">
         <div id="c" onclick="func">
         </div>
    </div>
</div>

When a click is made on a div it makes it's children invisible - ie click on "a" will turn "b" and "c" invisible.

function func{
   if ($(childId).hasClass("visible")){
    $(childId).removeClass("visible");
    $(childId).addClass("invisible");
}

The problem is: a click on "b" will call "a"'s click and make "b" and "c" invisible. How do I disable the click on "a" using jQuery?

thanks

2条回答
初与友歌
2楼-- · 2018-12-31 09:35

use

event.stopPropagation()

Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.

when click on b and c

查看更多
余生请多指教
3楼-- · 2018-12-31 09:42

You can add a handler for the child that will prevent the click event from propagating up:

function handler(event) {
    event.stopPropagation();
    // now do your stuff        
}
$('#a').add('#b').click(handler);

This way clicks to '#b' will not propagate to '#a'. Neither will clicks to '#c' go to '#b', and hence not to '#a'.

查看更多
登录 后发表回答