jQuery('#warning').click(function() {
console.log('clicked at warning');
});
jQuery('#content').click(function() {
console.log('clicked at content');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="warning">
<div id="content">This is the content</div>
dsfdfsdsfdsfdsfdsfdsfdsf
</div>
&#13;
小提琴:https://jsfiddle.net/73jykhj0/
不幸地点击content
也会触发点击warning
。如何消除点击warning
?
答案 0 :(得分:7)
使用Is it possible to use jQuery .on and hover?
防止事件冒泡
jQuery('#warning').click(function() {
console.log('clicked at warning');
});
jQuery('#content').click(function(event) {
event.stopPropagation()
console.log('clicked at content');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="warning">
<div id="content">This is the content</div>
dsfdfsdsfdsfdsfdsfdsfdsf
</div>
或者,您可以使用event.stopPropagation()
检查事件的目标,然后执行必要的操作。
jQuery('#warning').click(function(event) {
if ($(event.target).is('#content')) {
return;
}
console.log('clicked at warning');
});
jQuery('#content').click(function() {
console.log('clicked at content');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="warning">
<div id="content">This is the content</div>
dsfdfsdsfdsfdsfdsfdsfdsf
</div>
答案 1 :(得分:2)
见下文。点击内容即可添加return false
。
jQuery('#warning').click(function() {
alert('clicked at warning');
});
jQuery('#content').click(function() {
alert('clicked at content');
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="warning">
<div id="content">This is the content</div>
dsfdfsdsfdsfdsfdsfdsfdsf
</div>