单击除特定div以外的正文 [英] click on body except on specific div

查看:66
本文介绍了单击除特定div以外的正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了单击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以外的正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆