简体   繁体   English

从DOM中删除被单击的元素时,是否检测到单击元素外部的任何位置?

[英]Detecting when clicking anywhere outside of element when the clicked element has been removed from the DOM?

I have a notifications dropdown menu that should be closed when you click anywhere outside of it. 我有一个通知下拉菜单,当您单击菜单外的任何位置时,都应关闭它。 The following code was working great until I ran into a new situation: 在遇到新情况之前,以下代码非常有效:

$(document).click(function(e) {
    var target = e.target;

    if (!$(target).is('.notification-area') && !$(target).parents().is('.notification-area')) {
        $('.notification-area .flyout').removeClass('flyout-show');
    }
});

However (and I'm using Backbone if that's relevant), some elements cause part of the menu to re-render. 但是(如果相关,我正在使用Backbone),某些元素导致菜单的一部分重新呈现。 That is to say: remove and rebuild a part of the DOM. 也就是说:删除并重建DOM的一部分。

Obviously you can't tell where an element is within the DOM if it's already been removed. 显然,如果元素已被删除,则无法确定元素在DOM中的位置。 So now, if there's a click that causes part of that view to re-render then that bit of code that checks the parents() of the element returns no parents. 因此,现在,如果单击导致该视图的一部分重新呈现,则检查该元素的parents()的那部分代码将不返回任何父项。

Then I thought I might be able to solve it by checking if the length of parents() is greater than 0. 然后我认为我可以通过检查parents()的长度是否大于0来解决它。

...
if (!$(target).is('.notification-area') 
    && !$(target).parents().is('.notification-area')
    && $(target).parents().length > 0)
...

And this works but I wonder what side effects it could have. 这行得通,但我想知道它可能会有什么副作用。 Is this the best way to do this? 这是最好的方法吗?

Hope I understood your question correct. 希望我理解您的问题正确。 You want some simple way of not shutting the notification area if clicked upon it. 您需要一些简单的方法来在单击通知区域时不将其关闭。 But close it when clicked on body? 但是在点击身体时将其关闭?

One way to do these kind of things is somewhat like this. 做这类事情的一种方法有点像这样。

mouseOverArea = false; // This will be globally set, right away

$('.notification-area').mouseenter(function(){
    mouseOverArea = true;
}).mouseleave(function(){
    mouseOverArea = false;
});

And then when you click on body or whatever, you simply check if mouseOverArea == false... If so, close the notification box, otherwise return false, e.preventDefault(); 然后,当您单击主体或其他任何东西时,只需检查mouseOverArea == false ...如果是,则关闭通知框,否则返回false,e.preventDefault();。 or whatever fits your coding. 或任何适合您的编码。

You can simplify this using closest() since it includes both the target and ancestors. 您可以使用closest()简化此过程,因为它同时包含目标和祖先。

It turns : 事实证明 :

!$(target).is('.notification-area') && !$(target).parents().is('.notification-area')

Into a simpler to read: 变成一个更简单的阅读:

!$(target).closest('.notification-area').length

reference: closest() docs 参考: 最近的()文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM