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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:27:44  来源:igfitidea点击:

Preventing Child from firing parent's click event

javascriptjquerycss

提问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 clickassociated with it. How do I make sure that the live clickis not triggered when I clickanywhere 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я

you can do this by add a click event on the inner div and use either return false;or event.stopPropagation();

您可以通过在内部 div 上添加点击事件并使用return false;event.stopPropagation();

$(".div-inner").click(function(){

  return false;
})

or

或者

$(".div-inner").click(function(event){

  event.stopPropagation();
})

jsFiddle

js小提琴

回答by Talha Ahmed Khan

Create new clicklistener 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();
});