2013-04-23 87 views
2
<div id="firstDiv" style="width:1000px;height:600px;"> 
    <div id="secondDiv" style="width:200px;height:200px;"></div> 
</div> 

这两个DIV都有click()事件。当我点击secondDiv时,firstDiv的点击事件也被触发(我猜这是逻辑,因为我也在firstDiv的边框内点击了)。然而,我只想触发DIV的点击事件,点击时我实际上已经将鼠标移到了上面。如何点击()只点击DIV,不包含DIV?

我该如何做到这一点?

+3

重复http://stackoverflow.com/questions/2015041/two-differents-onclick-on-two-divs-one-over-the-other – Mandar 2013-04-23 20:35:35

+0

[click - only on“direct”onclicks]( http://stackoverflow.com/questions/6512803/click-only-on-direct-onclicks) – Nope 2013-04-24 17:18:51

+0

['event.stopPropagation'](http://api.jquery.com/event.stopPropagation/)? – 2013-04-24 19:29:00

回答

10

在内部的div加:

$('#secondDiv').click(function(e){e.stopPropagation();}); 

.stopPropagation()将阻止点击事件从内部DIV向上冒泡到父股利或任何其他的祖先。

5

默认情况下,DOM元素会冒起事件。您可以通过停止使用stopPropagation

$('#secondDiv').on('click', function(e){ 
    e.stopPropagation(); 
}); 
+0

@ user125697我想你使用了'preventDefault'。你应该使用'stopPropagation' – 2013-04-23 20:38:23

+0

我的错误。别担心 :) – lifetimes 2013-04-23 20:38:54

1

你可以做这一点 -

$('#secondDiv').click(function(event) { 
    // do your stuff 
    return false; 
}); 

return false;是相当于event.stopPropagation()event.preventDefault()

0

您可以使用event.stopPropagation()这个冒泡。事情是这样的:

$("secondDiv").click(function(event) { 
    event.stopPropagation(); 
    //Write your logic here 
}); 

欲了解更多有关该参考文档HERE

1

你会想使用event.stopPropagation()这将阻止事件向上冒泡到父元素(你的情况)。 preventDefault看起来很有希望,但它实际上可以防止默认操作 - 不冒泡。

$("#firstDiv").click(function() { 
    alert("Div One"); 
}); 

$("#secondDiv").click(function(e) { 
    e.stopPropagation(); 
    alert("Div Two"); 
}); 

演示两种here的。