jQuery 点击 $(document) - 获取被点击的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8945825/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:17:28  来源:igfitidea点击:

jQuery on click $(document) - get clicked element

jqueryclickhide

提问by user398341

I'm trying to figure out how to get the clicked element whey using $(document).click() method:

我试图弄清楚如何使用 $(document).click() 方法获取单击的元素乳清:

$(document).click(function() {
    if ($(this) !== obj) {
        obj2.hide();
    }
});

In the example above the objis the object is the dropdown menu - and if clicked I don't want it to do anything, but if the click was on the body of the page or any other element - it should trigger the hide() method.

在上面的例子中,obj是对象是下拉菜单 - 如果点击我不希望它做任何事情,但如果点击是在页面的正文或任何其他元素上 - 它应该触发 hide()方法。

回答by Frédéric Hamidi

You can use event.target. You should also compare DOM elements instead of jQuery objects, since two jQuery objects containing the same elements will still be considered as different:

您可以使用event.target。您还应该比较 DOM 元素而不是 jQuery 对象,因为包含相同元素的两个 jQuery 对象仍将被视为不同:

$(document).click(function(event) {
    if (event.target !== obj[0]) {
        obj2.hide();
    }
});

回答by Esailija

You most likely want to check all parent elements + the target itself for .topNavigationclass

您很可能想检查所有父元素 + 目标本身的.topNavigation

$(document).click(function(event) {
    if ( !$(event.target).closest( ".topNavigation" ).length ) {
        obj2.hide();
    }
});