可能是重复问题:
jQuery:点击函数排除子元素。
我有两个 div
,类似于这样:
<div id="parent" style="width: 100%; height: 100%; background-color:red;" />
<h1>I'm the parent!</h1>
<div id="child" style="width: 300px; height: 200px; background-color:yellow;">
</h2>..and I'm the child!</h2>
</div>
</div>
此外,我有以下JavaScript代码:
$(document).ready(function(){
$('#parent').click(function(){
alert('Parent was clicked');
});
});
问题是,如果我点击子元素,事件就会被触发。如何将此事件限制在父元素中呢?
编辑:为了澄清,我希望当用户在红色区域的任何位置单击时都会触发此操作。正如评论中所说,
h1
不是父元素。Tjirp的答案解决了问题,并且有很多这种解决方案的变体在答案中可用。