【发布时间】:2015-10-28 09:50:40
【问题描述】:
我有一个导航,我想在单击按钮时打开它。当导航打开并且用户在导航外部单击时,我希望它关闭。我以为很容易......
我尝试通过在按钮上首先单击事件来打开导航来实现这一点。然后我在文档上添加一个触发 closeNav 方法的新点击事件。
到目前为止,一切都很好。有用。但是我的点击事件堆积起来。每次打开导航时都会添加一个新的文档单击事件。所以我添加了一个关闭点击来移除之前添加的点击事件。也尝试了 unbind,结果相同。
我的猜测它与处理程序有关,因为我使用 this.closeNav.bind(this)。但我不知道...
有什么想法吗?
headerNavigation.prototype.init = function()
{
// Add on click event on the button that triggers toggleNavigation
$(this.navBtn).on('click', this.toggleNavigation.bind(this));
}
headerNavigation.prototype.toggleNavigation = function(e)
{
e.stopPropagation();
$(this.nav).slideToggle(200);
// Add an on click for document that triggers this.closeNav
$(document).on('click', this.closeNav.bind(this));
}
headerNavigation.prototype.closeNav = function(e)
{
console.log($(document).data('events'));
$(this.nav).slideUp(200);
// Now remove the on click event for document so we do not stack up on these
$(document).off('click', this.closeNav.bind(this));
}
【问题讨论】:
-
bind返回一个新函数。您需要将对该函数的引用存储在某处
标签: javascript jquery javascript-events event-handling