gpt4 book ai didi

javascript - 在 jquery 事件中引用 javascript 对象

转载 作者:行者123 更新时间:2023-11-30 18:20:28 27 4
gpt4 key购买 nike

我有这个代码。

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 以便我可以调用该函数。

最佳答案

在绑定(bind) 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();
});
}

关于javascript - 在 jquery 事件中引用 javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12158406/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com