在jquery事件中引用javascript对象

Referencing javascript object within jquery event

本文关键字:javascript 对象 引用 jquery 事件      更新时间:2023-09-26

我有这段代码。

var NotificationsBox={
    HideNotificationBox:function()
    {
          document.getElementById("NotificationBox").style.visibility="hidden"; 
    },
    toggleNotificationBox:function()
    {
        $('#NotificationBox').toggle();             
    },
    SetContainerClick_NotificationHide_Event:function()
    {
        $('#Container').click(this.HideNotificationBox);        
    },
    SetNotificationBoxClick_NotificationToggleEvent:function()
    {
        $('#ShowNotification').click(function(){
            $(this).html("0");
            $(this).css("background-color","#000");
            this.toggleNotificationBox();     ///  <-- PROBLEM
        });
    }
};
NotifyBox=Object.create(NotificationsBox);
NotifyBox.HideNotificationBox();
NotifyBox.SetContainerClick_NotificationHide_Event();
NotifyBox.SetNotificationBoxClick_NotificationToggleEvent();

现在你可以看到问题是什么了。这里this将引用#ShowNotification,我想在这里引用NotificationBox,这样我就可以调用函数了。

在绑定click之前保存对this的引用,并在click事件处理程序中使用此引用而不是this

SetNotificationBoxClick_NotificationToggleEvent:function()
{
    var self = this;
    $('#ShowNotification').click(function(){
        $(this).html("0");
        $(this).css("background-color","#000");
        self.toggleNotificationBox(); //  <-- self will refer to NotificationsBox
    });
}

或者,作为一种选择,使用NotificationsBox.toggleNotificationBox(),但如果您碰巧更改了变量NotificationsBox:的名称,这将停止工作

SetNotificationBoxClick_NotificationToggleEvent:function()
{
    $('#ShowNotification').click(function(){
        $(this).html("0");
        $(this).css("background-color","#000");
        NotificationsBox.toggleNotificationBox();
    });
}