Javascript jQuery单击除div和it之外的所有内容';孩子们

Javascript jQuery单击除div和it之外的所有内容';孩子们,javascript,jquery,Javascript,Jquery,我想在单击任意位置时做一些事情,但单击div及其子对象时除外。这是我到目前为止尝试过的,但它不起作用(单击它的子项仍然执行括号内的内容) $('body').on('click', '* :not(#calculator)', function(e){ 我不能用这样的东西: 因为.not函数不是我可以放在.on()函数中的东西 如何实现这一点?您可以在函数内部检查相关元素: $('body').click( function(e){ if (!$(e.target).is("#ca

我想在单击任意位置时做一些事情,但单击div及其子对象时除外。这是我到目前为止尝试过的,但它不起作用(单击它的子项仍然执行括号内的内容)

$('body').on('click', '* :not(#calculator)',  function(e){
我不能用这样的东西:

因为
.not
函数不是我可以放在
.on()
函数中的东西


如何实现这一点?

您可以在函数内部检查相关元素:

$('body').click( function(e){
    if (!$(e.target).is("#calculator") || $("#calculator").has(e.target).length ) {
        // do your stuff
    }
});

使用not和逗号可以同时使用选择器:元素本身和元素子元素

jQuery(document.body).on("click", ":not(#calculator, #calculator *)", function(e){ 
    console.log(this); 
    e.stopPropagation(); 
});​​​​​​​
而不是

$('body').on('click', '* :not(#calculator)',  function(e){

});​
您可以使用(此版本是首选,因为它更具性能)


我没有足够的要求来添加推荐,所以我需要在这里向@epascarello提问。当我生了几个孩子时,A和B仍然受到影响。我不确定我是否错了,但我真的想得到解决方案

jQuery(document.body).on("click", ":not(#calculator, #calculator *)", function(e){ 
    console.log(this); 
    e.stopPropagation(); 
    alert('test');
});

在childs中添加一个类,然后进行检查?你不认为这会简单得多吗?我要排除的div非常大,很可能每次我都会忘记添加特定的类。也许你已经对此有所了解了???元素气泡,这就是为什么它会在#calculator元素上触发,你必须检查目标t是#calculator或calculator元素#本身的子元素。@Bax你说得对,更新了我的答案以检查后代。是的,那太棒了:)不过我还是更喜欢epascarello的答案,因为它让我的代码更干净了:)不是
$(“#计算器”).has(e.target)
始终
false
?是不是应该是
($(“#计算器”).has(e.target).length>0)
?@Micah我提交了一份带有更正答案的编辑,使用javascript truthy/falsy值,我们可以将表达式简化为
(“#计算器”).has(e.target).length
看到你的答案违背了
on
的目的。是的,它可以工作,但您正在向页面添加许多单击处理程序。
$("body").on("click", ":not(#calculator, #calculator *)", function(e){ 

});​
$("body :not(#calculator, #calculator *)").on("click", function(e){ 

});​
jQuery(document.body).on("click", ":not(#calculator, #calculator *)", function(e){ 
    console.log(this); 
    e.stopPropagation(); 
    alert('test');
});