单击$(文档)上的jQuery - 获取单击元素

时间:2021-10-19 21:20:39

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 obj is 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()方法。

2 个解决方案

#1


22  

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();
    }
});

#2


12  

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

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

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

#1


22  

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();
    }
});

#2


12  

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

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

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