[英]jQuery click event won't unbind
我有一个导航,当我单击一个按钮时要打开它。 当导航打开并且用户在导航之外单击时,我希望它关闭。 容易我以为...
我尝试首先在按钮上单击事件以打开导航来实现此目的。 然后我在触发 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 每次调用它时都会创建一个新函数。
尝试这个:
headerNavigation.prototype.toggleNavigation = function(e)
{
e.stopPropagation();
$(this.nav).slideToggle(200);
// Add an on click for document that triggers this.closeNav
this._binder = this.closeNav.bind(this);
$(document).on('click', this._binder);
}
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._binder);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.