2010-03-05 73 views
37

只是一个简单的问题。我在互相之间使用onclick javascript处理div问题。当我点击内部div时,它应该只会触发它的onclick javascript,但外部div的javascript也被解雇了。如何在不触发外部div的javascript的情况下点击内部div?Howto:div与onclick另一个div与onclick javascript

<html> 
<body> 
<div onclick="alert('outer');" style="width:300px;height:300px;background-color:green;padding:5px;">outer div 
    <div onclick="alert('inner');" style="width:200px;height:200px;background-color:white;" />inner div</div> 
</div> 
</div> 
</body> 
</html> 
+1

重复。 http://stackoverflow.com/questions/2015041/two-differents-onclick-on-two-divs-one-over-the-other – vpram86 2010-03-05 07:16:38

+4

重复的问题,但更好的答案。 – 2011-02-16 01:46:11

回答

70

基本上有在JavaScript这两种事件模型。 事件捕获事件冒泡。在事件冒泡中,如果您点击div内部,则首先触发inside div click事件,然后触发外部div点击。而在事件捕获中,首先触发外部div事件并触发内部div事件。要停止事件传播,请在点击方法中使用此代码。

if (!e) var e = window.event; 
    e.cancelBubble = true; 
    if (e.stopPropagation) e.stopPropagation(); 
+0

谢谢,一个简单的明确答案,并完美的作品 – 2010-03-05 07:37:05

+1

谢谢。优秀的答案;就是我在找的东西。 – 2012-11-22 03:34:52

5

return false;从内部的div的onclick功能:

<div onclick="alert('inner'); return false;" ... 

什么你正在处理被称为event propagation

+0

您建议的方法实际上不起作用。 (至少不是在任何浏览器中,我只是加倍检查它 - Firefox 3.6,IE8。)请注意,您的链接实际上表示使用不同的方法,我在回答中给出了。 – 2010-03-05 07:37:57

17

退房事件传播的信息here

特别是你要在你的事件处理一些像这样的代码来传播停止事件:

function myClickHandler(e) 
{ 
    // Here you'll do whatever you want to happen when they click 

    // now this part stops the click from propagating 
    if (!e) var e = window.event; 
    e.cancelBubble = true; 
    if (e.stopPropagation) e.stopPropagation(); 
} 
+0

谢谢!这对我 – CraZyDroiD 2017-09-12 11:15:58

2

这是事件冒泡的情况下, 。

您可以使用

e.cancelBubble = true; //IE 

e.stopPropagation(); //FF 
+0

花了一段时间了解,但现在得到它,thx – 2010-03-05 07:37:41

0

Here是一些参考资料,以便帮助您了解JavaScript事件冒泡。

0

你有两个'div'和三个'/ div'。基于WebKit浏览器

2

另一种方式:

<div onclick="alert('inner'); event.stopPropagation;" ... 
+1

这个工作,但是像这样:onclick =“alert('inner'); event.stopPropagation();” – 2015-12-10 12:29:08

+0

这工作对我和我在Opera(46),Chrome(59.0.3071.115),FireFox开发人员(55.0b9(32位)),Internet Explorer 11 – 2017-07-19 19:09:43

0

这是非常有益的,但它并没有为我工作。我所做的是here

所以我把一个条件外onclick事件:

if(!event.isPropagationStopped()) { 
    window.location.href = url; 
} 
4

只需添加以下代码:

window.event.stopPropagation(); 
+0

测试它这没有为我工作。最重要的答案是更准确。 – 2015-12-18 11:00:45

0

您可以使用

$("divOrClassThatYouDontWantToPropagate").click(function(event) { 
 
     event.stopPropagation(); 
 
    });