I wonder how can I stop child onclick event while still triggering the parent onclick event. For example the following structure:
<div id="parent">
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
</div>
if I click "child1" for example, the onclick event for "child1" will not be triggered, however, the onclick event for "parent" will still be triggered.
Thank you very much!
最简单的方法是取消绑定孩子的事件处理程序。
$('#child1').unbind('click');
You could just pass the click
to the parent?
$('.child1').click(function(e){
e.preventDefault();
$(this).parent('#parent').trigger('click');
});
When you click .child1, it will prevent the default action, and then trigger the click for the parent of child1
with an id of #parent.
Actually - probably ignore the above - as per the comment below it may cause bubbling. All you really need to do is use e.stopPropagation();
.
I've created a jsfiddle showing how although the child1
has a click function bound to it, it's being ignored, and so the parent click is only getting picked up.
Here is a solution bin for above issue. please check demo link once.
Demo: http://codebins.com/bin/4ldqp7l
HTML
<div id="parent">
<div id="child1">
Child-1
</div>
<div id="child2">
Child-2
</div>
<div id="child3">
Child-3
</div>
</div>
jQuery
$(function() {
$("#parent").click(function() {
alert("Parent has been clicked too...!");
});
$("#child1").click(function(e) {
e.stopPropagation();
alert("Child-1 has been clicked...!");
});
$("#child2").click(function() {
alert("Child-2 has been clicked...!");
});
$("#child3").click(function() {
alert("Child-3 has been clicked...!");
});
});
CSS
#parent{
padding:5px;
background:#a34477;
width:140px;
text-align:center;
padding:10px;
}
#parent div{
border:1px solid #2211a4;
background:#a3a5dc;
width:100px;
text-align:center;
font-size:14px;
margin-left:10px;
margin-top:3px;
}
do you mean:
$('#parent').on('click', function(e) {
if( e.target !== this ) {
return;
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.