jquery 文档正文一键事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1925097/
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 document body one click event
提问by Manuel
Could somebody help me with this? :
有人可以帮我解决这个问题吗?:
I have a button that when clicked it shows a certain div. This div has several descendants. Now, what I want is that when I click somewhere else in the document, but not in any of those descendantsthat this div disappears. what I thought was to use the not selector like this:
我有一个按钮,单击它时会显示某个 div。这个 div 有几个后代。现在,我想要的是,当我单击文档中的其他位置时,而不是在此 div 消失的任何后代中。我想的是像这样使用 not 选择器:
$("#button").click(function(){
$("#mydiv").show();
$(document.body).not($("#mydiv").children()).one('click',function(e) {
$("#mydiv").hide();
});
return false;
});
but this is not working! Any idea why? thanks
但这不起作用!知道为什么吗?谢谢
回答by Topher Fangio
How about checking the click event to see what was clicked? Specifically look at the event.target
.
如何检查点击事件以查看点击了什么?具体看event.target
.
$(document).click(function(event) {
var target = $(event.target);
if (!target.attr('id').match(/^mydiv/) && target.parents('#mydiv').length == 0) {
$('#mydiv').hide();
}
});
I have used this code before to close an open window when someone clicks anywhere but the window.
当有人点击窗口以外的任何地方时,我之前曾使用此代码关闭打开的窗口。
回答by Joel
Use closest to check if the target is a descendant of mydiv
.
使用最接近检查目标是否是 的后代mydiv
。
$("#button").click(function(){
$("#mydiv").show();
$(document.body).click(function() {
if ($(event.target).closest("#mydiv").length == 0)
$("#mydiv").hide();
});
return false;
});
You can't use one()
because the event would get removed if you click inside mydiv
. You'll have to do some custom event unbinding if you want to remove it.
你不能使用,one()
因为如果你点击 inside 事件会被删除mydiv
。如果要删除它,则必须执行一些自定义事件解除绑定。
回答by Russ Cam
The problem might be with what you are passing in to the .not()
to exclude
问题可能在于您传递给.not()
要排除的内容
.not($("#mydiv").children())
At the moment you are passing a jQuery object in, but from the docs, what is passed into .not()
should be either a string selector, a DOM element or an array of DOM elements. Therefore simply converting the jQuery object to an array of elements should work
目前您正在传入一个 jQuery 对象,但从docs 中,传入的.not()
应该是字符串选择器、DOM 元素或 DOM 元素数组。因此,只需将 jQuery 对象转换为元素数组即可
$("#button").click(function(){
var myDiv = $("#mydiv").show();
$(document.body).not(myDiv.children().get()).one('click',function(e) {
myDiv.hide();
});
return false;
});