Javascript 通知分区-下拉关闭

Javascript 通知分区-下拉关闭,javascript,jquery,html,asp.net-mvc,Javascript,Jquery,Html,Asp.net Mvc,我有一个类似stackoverflow的通知下拉列表。因此,当用户请求通知窗口时,我使用.show和.hide打开和关闭下拉div 同时,我还想在用户单击我的下拉列表以外的任何位置时关闭它 我的方法是在我的布局.cshtml上执行以下操作: $(document).on("click", onDocumentClick); function onDocumentClick(event) { var target = $(event.target); if (!target.ha

我有一个类似stackoverflow的通知下拉列表。因此,当用户请求通知窗口时,我使用
.show
.hide
打开和关闭下拉div

同时,我还想在用户单击我的下拉列表以外的任何位置时关闭它

我的方法是在我的布局.cshtml上执行以下操作:

$(document).on("click", onDocumentClick);

function onDocumentClick(event) {
    var target = $(event.target);
    if (!target.hasClass('nbr-notifications')) {
        if ($('#notifications-dropdown').css('display') === 'block') {
            $('#notifications-dropdown').hide();
        }
    }
}

我的问题和担忧是:这是最好的方式吗?从性能的角度来看?因为我每次都在处理文档上的所有单击操作。

如果您不确定元素将在哪里,您就不能使用它吗

    $('body').on("click",".nbr-notifications", onClick)
  .on('blur','.nbr-notifications',closeNotifications);

function onClick(event) {        

        if ($('#notifications-dropdown').css('display') === 'block') {
            $('#notifications-dropdown').hide();

    }
}

function closeNotifications()
{
//close it
}

此处仅对类为“nbr notifications”的元素上的单击进行响应,而不是挂起所有单击的事件处理程序,并检查目标是否为必需的。如果希望通知在失去焦点后消失,为什么不将focusout事件专门绑定到该元素,而不是单击整个元素文件


我将其应用于#通知下拉列表,但无法将其应用。它不会开火。当我在我的
#notifications下拉列表
div外单击时,什么都没有发生。ThanksI尝试过,但我的div没有触发事件。我尝试过使用输入文本框,但效果很好。因此,不知何故,该代码不适用于div.Thanksolution,可在此处找到:
$('.nbr-notifications').on('focusout',function(){ 
    //close functionality here.  something like: $(this).hide();
});