javascript 如何使用 jQuery 确定是否在特定元素内触发了单击事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4432032/
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
How can I use jQuery to determine if a click event fires within a specific element?
提问by WNRosenberg
I'm using the following code to animate a block.  In my code, div_animate()essentially hides a <div>with the specified selector if it is currently visible.  
我正在使用以下代码为块设置动画。在我的代码中,如果指定的选择器当前可见,它div_animate()本质上是隐藏的<div>。  
$(document).click(function(event){
    div_animate("#container");
});
I need to determine whether the user clicked on a child of #containerand if so, return false;-- as far as I can tell, the code for this would look something like this:
我需要确定用户是否点击了一个孩子,#container如果是,return false;——据我所知,这个代码看起来像这样:
$(document).click(function(event){
    if ( /* the event's target has a parent of #container */ ) {
        return false;
    } else {
        div_animate("#container");
    }
});
Any thoughts?
有什么想法吗?
回答by Pointy
The simplest thing would be:
最简单的事情是:
if ($(event.target).is('#container *, #container')) // edited - thanks @gnarf
  // is a child
else
  // is not a child
There are different choices you could make for detecting whether it's a child of the target (or non-target) container; that's just one. An alternative:
您可以做出不同的选择来检测它是否是目标(或非目标)容器的子项;那只是一个。替代:
if ($(event.target).closest('#container').length)
回答by Nick Craver
You can prevent the action if the click originated on or in #container, like this:
如果点击来自 或#container,您可以阻止该操作,如下所示:
$(document).click(function(event){
    var c = $("#container")[0];
    if (event.target == c || $.contains(c, event.target)) {
        return false;
    } else {
        div_animate("#container");
    }
});
The first check is if it came from #containeritself, the second is if it came from a child, that #container$.contains().  A completely alternative, simpler way is to just prevent the bubble up to documentwhen clicking on #container, like this:
第一个检查是它是否来自#container它自己,第二个是它是否来自一个孩子,那个#container$.contains(). 一种完全替代的、更简单的方法是document在单击 时防止气泡#container,如下所示:
$("#container").click(function(e) {
  e.stopPropagation();
});
$(document).click(function() {
  div_animate("#container");
});

