javascript 防止孩子触发父母的点击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13682435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Preventing Child from firing parent's click event
提问by Udai Arora
Consider the following snippet:
考虑以下片段:
<div class="div-outer">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<div class="div-inner" style="background:red">
Curabitur hendrerit vehicula erat, ut gravida orci luctus vitae.
</div>
</div>
Now suppose the outer div has a live click
associated with it. How do I make sure that the live click
is not triggered when I click
anywhere in the inner div
?
现在假设外部 div 有一个click
与之关联的 live 。click
当我click
在内部的任何地方时,如何确保不会触发live div
?
Edit:
编辑:
Here's the JS as requested
这是要求的JS
$(".div-outer").live("click",function(){alert("hi")});
This should not be triggereed when clicking on ".inner-div"
单击“.inner-div”时不应触发此操作
回答by Zeta
You have to add an event listener to the inner child and cancel the propagation of the event.
您必须向内部孩子添加一个事件侦听器并取消事件的传播。
In plain JS something like
在普通的 JS 中类似
document.getElementById('inner').addEventListener('click',function (event){
event.stopPropagation();
});
is sufficient. Note that jQuery provides the same facility:
足够了。请注意,jQuery 提供了相同的功能:
$(".inner-div").click(function(event){
event.stopPropagation();
});
or
或者
$(".inner-inner").on('click',function(event){
event.stopPropagation();
});
回答by TheDarkIn1978
An alternative solution is to add a CSS Pointer Eventsrule to the child element:
另一种解决方案是向子元素添加CSS Pointer Events规则:
CSS:
CSS:
#childElement {
pointer-events: none;
}
JavaScript:
JavaScript:
document.getElementById("childElement").style.pointerEvents = "none";
document.getElementById("childElement").style.pointerEvents = "none";
回答by NullPoiиteя
回答by Talha Ahmed Khan
Create new click
listener for the inner div and call the event.stopPropagation()
in that new event.
click
为内部 div创建新的侦听器并event.stopPropagation()
在该新事件中调用。
like
喜欢
$('div-outer').on('click','div-inner',function(e){
e.stopPropagation();
});
回答by Bal mukund kumar
use stopPropagation in your js file
在你的 js 文件中使用 stopPropagation
$(".eventclick").click(function(e) {
e.stopPropagation();
});