[英]JQuery: How to stop child onclick event while still triggering the parent onclick event
I wonder how can I stop child onclick event while still triggering the parent onclick event. 我想知道如何在触发父onclick事件的同时停止子onclick事件。 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. 例如,如果单击“child1”,则不会触发“child1”的onclick事件,但仍会触发“parent”的onclick事件。
Thank you very much! 非常感谢你!
最简单的方法是取消绑定孩子的事件处理程序。
$('#child1').unbind('click');
You could just pass the click
to the parent? 你可以将
click
传递给父母?
$('.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. 当您单击.child1,它会阻止默认操作,然后触发点击的父
child1
与#parent的ID。
Actually - probably ignore the above - as per the comment below it may cause bubbling. 实际上 - 可能会忽略上述内容 - 根据下面的评论,它可能会导致冒泡。 All you really need to do is use
e.stopPropagation();
你真正需要做的就是使用
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. 我创建了一个的jsfiddle展示如何虽然
child1
上绑定了一个点击功能,它被忽略,所以父点击只得到回升。
Here is a solution bin for above issue. 这是上述问题的解决方案箱。 please check demo link once.
请查看演示链接一次。
Demo: http://codebins.com/bin/4ldqp7l 演示: http : //codebins.com/bin/4ldqp7l
HTML HTML
<div id="parent">
<div id="child1">
Child-1
</div>
<div id="child2">
Child-2
</div>
<div id="child3">
Child-3
</div>
</div>
jQuery 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 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;
}
Demo: http://codebins.com/bin/4ldqp7l 演示: http : //codebins.com/bin/4ldqp7l
do you mean: 你的意思是:
$('#parent').on('click', function(e) {
if( e.target !== this ) {
return;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.