如何点击()只点击DIV,不包含DIV?

Mat*_*der 2 html javascript jquery

<div id="firstDiv" style="width:1000px;height:600px;">
    <div id="secondDiv" style="width:200px;height:200px;"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

两个DIV都有click()事件.当我单击secondDiv时,firstDiv的click事件也被触发(我猜这是逻辑,因为我也点击了firstDiv的边框内).然而,我只想点击DIV的点击事件,实际上我点击了鼠标.

我怎么能做到这一点?

j08*_*691 10

在内部div添加:

$('#secondDiv').click(function(e){e.stopPropagation();});
Run Code Online (Sandbox Code Playgroud)

.stopPropagation() 将阻止click事件从内部div冒泡到父div或任何其他祖先.


Tej*_*eni 5

默认情况下,DOM元素会使事件冒泡.您可以使用stopPropagation停止

$('#secondDiv').on('click', function(e){
    e.stopPropagation();
});
Run Code Online (Sandbox Code Playgroud)