![](/img/trans.png)
[英]jQuery - div inside div, how to run only 1 click event when inside has been clicked
[英]how to click() only clicked DIV, not containing DIV?
<div id="firstDiv" style="width:1000px;height:600px;">
<div id="secondDiv" style="width:200px;height:200px;"></div>
</div>
两个DIV都有click()事件。 当我单击secondDiv时,firstDiv的click事件也被触发(我猜这是逻辑,因为我也点击了firstDiv的边框内)。 然而,我只想点击DIV的点击事件,实际上我点击了鼠标。
我怎么能做到这一点?
在内部div添加:
$('#secondDiv').click(function(e){e.stopPropagation();});
.stopPropagation()
将阻止click事件从内部div冒泡到父div或任何其他祖先。
默认情况下,DOM元素会使事件冒泡。 您可以使用stopPropagation停止
$('#secondDiv').on('click', function(e){
e.stopPropagation();
});
你可以这样做 -
$('#secondDiv').click(function(event) {
// do your stuff
return false;
});
return false;
相当于event.stopPropagation()
和event.preventDefault()
你需要使用event.stopPropagation()
来防止事件冒泡到父元素(在你的情况下)。 preventDefault
看起来很有希望,但实际上它可以防止默认操作 - 而不是冒泡。
$("#firstDiv").click(function() {
alert("Div One");
});
$("#secondDiv").click(function(e) {
e.stopPropagation();
alert("Div Two");
});
在这里演示。
您可以使用event.stopPropagation()
进行此冒泡。 像这样的东西:
$("secondDiv").click(function(event) {
event.stopPropagation();
//Write your logic here
});
有关此内容的更多信息,请参阅此处的文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.