问题描述
除了单击body
内的menutop
之外,我还想单击body
.
I want to do something clicking on body
, except on menutop
which is inside the body
.
<body>
<div id="menutop">lorem ipsum...</div>
...
</body>
js
$("body").not($("#menutop")).click(function(){
console.log("323");
});
也尝试过
var n = $("#menutop");
$("body:not(n)").click(function(){
console.log("323");
});
,但在两种情况下都单击menutop
控制台会显示323
but clicking on menutop
in both cases console shows 323
推荐答案
如果选择器$("body").not($("#menutop"))
不是#menutop
元素,它将选择body
元素.由于body
元素显然不是#menutop
元素,因此仍选择了body
元素,并将click事件附加到该元素.
The selector $("body").not($("#menutop"))
will select the body
element if it is not the #menutop
element. Since the body
element clearly isn't #menutop
element, the body
element is still selected and the click event is attached to it.
即使您单击#menutop
元素,单击事件仍会冒泡并触发body
元素上的click事件,因此一种选择是检查event.target
是否为#menutop
元素:
Even if you click on the #menutop
element, the click event will still bubble up and trigger the click event on the body
element, therefore one option is to make a check to see if event.target
is the #menutop
element:
$(document).on('click', function (event) {
if (!$(event.target).closest('#menutop').length) {
// ... clicked on the 'body', but not inside of #menutop
}
});
或者,您也可以在点击添加"后,抑制事件冒泡和停止事件传播. #menutop
元素:
Alternatively, you could also suppress the event bubbling and stop event propagation when clicking in the #menutop
element:
$(document).on('click', function (event) {
// ... clicked on the 'body', but not inside of #menutop
});
$('#menutop').on('click', function (event) {
event.stopPropagation();
});
这篇关于单击除特定div以外的正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!