当孩子被点击时,如何停止点击事件触发父元素? [英] How can I stop an onclick event from firing for parent element when child is clicked?

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

问题描述



首先:



我有一个div的复选框。输入有一个onchange函数,div有一个onclick函数。

 < div onclick =doSomething()> 
< input type =checkboxonchange =doSomethingElse()/>
< / div>

问题是当我检查/取消选中doSomething()和doSomethingElse()的复选框。任何想法如何阻止这种发生?我试过做过onchange =doSomethingElse(event),而在doSomethingElse(e)函数中我有e.stopPropagation();这不行。



第二:



我有一个div的图像。 div有一个onclick功能,但是图像没有。图像的目的是大于div并在div外溢出。

  ---------- ------------- 
|图像|
| --------------- |
| | div | |
| | | |
| --------------- |
| |
-----------------------

如果用户在div框的边界内点击,我只想点击onclick。但是,如果您点击已经溢出到div外部的图像的一部分,onclick事件也将触发。任何想法?



第一个问题是对我来说比第二个更重要。但是如果有人可以回答这两件事情会很棒!



提前感谢您的帮助,
Matt

解决方案

对于您的第一个问题:IE不支持 stopPropagation(),而应该使用 e.cancelBubble = true 。首先要做一个函数检查,找出你应该使用哪种方法( if(e.stopPropagation){code} )。



对于您的第二个问题:也许包括处理点击事件的第二个div?

 < div>< img src =image.jpg/>< / div> 
< div style =position:absoluteonclick =doSomething();>< / div>

然后正确放置第二个div


I'm having two issues with onclick events, they are somewhat similar so I'll ask them both here.

First:

I have a checkbox in a div. The input has an onchange function and the div has an onclick function.

<div onclick="doSomething()">
     <input type="checkbox" onchange="doSomethingElse()" />
</div>

The problem is when I check/uncheck the checkbox both doSomething() and doSomethingElse() fire. Any ideas of how to stop this from occuring? I've tried doing onchange="doSomethingElse(event)" and the in doSomethingElse(e) function I had e.stopPropagation(); and this did not work.

Second:

I have an image in a div. The div has an onclick function but the image does not. The image is, purposely, larger than the div and overflows outside the div.

-----------------------
|        image        |
|   ---------------   |
|   |     div     |   |
|   |             |   |
|   ---------------   |
|                     |
-----------------------

I only want the onclick to fire if the user clicks within the bounds of the div box. However, the onclick event also fires if you click on a part of the image that has overflowed to the outside of the div... Any ideas?

The first question is more important to me than the second. But if someone can answer both that would be awesome!

Thanks in advance for your help,
Matt

解决方案

For your first question: IE doesn't support stopPropagation(), instead you should use e.cancelBubble = true. Just do a function check first to find out which method you should use (if (e.stopPropagation) {code}).

For your second question: Maybe include a second div that handles the click event?

<div><img src="image.jpg"/></div>
<div style="position:absolute" onclick="doSomething();"></div>

and then position the second div correctly

这篇关于当孩子被点击时,如何停止点击事件触发父元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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