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

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

问题描述

我有两个关于 onclick 事件的问题,它们有些相似,所以我会在这里问他们两个.

首先:

我在 div 中有一个复选框.input 有 onchange 函数,div 有 onclick 函数.

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

问题是当我选中/取消选中复选框时,doSomething() 和 doSomethingElse() 都会触发.关于如何阻止这种情况发生的任何想法?我试过做 onchange="doSomethingElse(event)" 和在 doSomethingElse(e) 函数中我有 e.stopPropagation();这没有用.

第二:

我在一个 div 中有一个图像.div 具有 onclick 功能,但图像没有.图像故意大于 div 并溢出 div.

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

如果用户在 div 框的边界内单击,我只希望 onclick 触发.但是,如果您单击溢出到 div 外部的图像部分,也会触发 onclick 事件...有任何想法吗?

第一个问题对我来说比第二个问题更重要.但如果有人能同时回答这两个问题,那就太棒了!

预先感谢您的帮助,
马特

解决方案

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

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

<div><img src="image.jpg"/></div><div style="position:absolute" onclick="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

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

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