javascript jQuery 单击除 div 之外的所有内容及其子项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12690313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery on click on everything but a div and it's children
提问by Timo Willemsen
I want to do something when I click anywhere, except when I click a div and it's children. This is what I've tried so far, but it's not working (clicking on it's children still executes what is within the brackets.
当我点击任何地方时,我想做一些事情,除非我点击一个 div 并且它是孩子。这是我迄今为止尝试过的,但它不起作用(点击它的孩子仍然执行括号内的内容。
$('body').on('click', '* :not(#calculator)', function(e){
I cannot use something like this:
我不能使用这样的东西:
jQuery - Select everything except a single elements and its children?
$("body > *").not("body > #elementtokeep").remove();
Because the .not
function is not something I can put inside the .on()
function.
因为.not
函数不是我可以放在.on()
函数里面的东西。
How can I achieve this?
我怎样才能做到这一点?
回答by epascarello
回答by Kh?i
You could check inside the function for the element in question:
您可以在函数内部检查相关元素:
$('body').click( function(e){
if (!$(e.target).is("#calculator") || $("#calculator").has(e.target).length ) {
// do your stuff
}
});
回答by lyhong
I don't have enough requirement to add commend, so I need to ask my question here to @epascarello. When I made few children, A and B still affected. I am not sure I am wrong or not, but I really want to get solution.
我没有足够的要求来添加推荐,所以我需要在这里向@epascarello提出我的问题。当我生几个孩子的时候,A和B仍然受到影响。我不确定我是否错了,但我真的很想得到解决方案。
jQuery(document.body).on("click", ":not(#calculator, #calculator *)", function(e){
console.log(this);
e.stopPropagation();
alert('test');
});
回答by prashanth
Instead of
代替
$('body').on('click', '* :not(#calculator)', function(e){
});?
You can use (this version is preferred as it is more performant)
您可以使用(此版本是首选,因为它的性能更高)
$("body").on("click", ":not(#calculator, #calculator *)", function(e){
});?
or
或者
$("body :not(#calculator, #calculator *)").on("click", function(e){
});?