Structure:
.parent (has if/else to toggle on click) -> .child (has nothing)
Parent
-
Use event.stopPropagation();
:
$('#a').add('#b').click(fun1);
function handler(event) {
event.stopPropagation();
// now do your stuff
}
讨论(0)
-
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)