当单击一个子元素时,如何防止触发点击处理程序? [英] How do I prevent a click handler being triggered when a child element is clicked?

查看:77
本文介绍了当单击一个子元素时,如何防止触发点击处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个div标签,第一个div是父亲,第二个div是儿子,在这样的父亲中这样

  ; div id =father> 
< div id =son> < / DIV>
< / div>

我已经在这样的div父亲中添加了一个事件(onclick)

 < div id =fatheronclick =closeFather()> 
< div id =son> < / DIV>
< / div>

我的问题是为什么儿子在事件中继承父亲。 / p>

我想要当我点击父亲div实现事件,但是当我点击儿子没有实现任何东西,因为它没有任何事件。

解决方案

您可以将事件作为 closeFather 函数中的参数之一传递,检查事件目标是否是父元素。请参阅此示例

  function closeFather(e){
if(e.target == document.getElementById('father')){
// do stuff
}
} ;

然后在HTML中,您只需要向javascript函数添加事件参数。

 < div id =fatheronclick =closeFather(event)> 
< div id =son>< / div>
< / div>


I have two div tags, first div is the father and the second div is son Inside the father like this

<div id="father"> 
<div id="son"> </div>
</div>

And I've added an event (onclick) in div father like this

<div id="father" onclick="closeFather()"> 
<div id="son"> </div>
</div>

My question is why the son inherits the father in the event.

I want when I click on the Father div implement the event, but when i click on the son does not implement anything because it does not have any event.

解决方案

You can pass the event as one of the arguments in the closeFather function, then check whether the event target is the father element. See this example

function closeFather(e) {
    if(e.target == document.getElementById('father')) {
        //do stuff
    }
};

Then in the HTML you just need to add the event argument to the javascript function.

<div id="father" onclick="closeFather(event)">
<div id="son"></div>
</div>

这篇关于当单击一个子元素时,如何防止触发点击处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆