Javascript 如何摧毁';Popstate';事件侦听器?
已尝试以下代码,但未销毁Javascript 如何摧毁';Popstate';事件侦听器?,javascript,popstate,removeeventlistener,Javascript,Popstate,Removeeventlistener,已尝试以下代码,但未销毁Popstate事件 请帮助我们举一个例子,在这个例子中,我可以根据条件销毁Popstate事件 history.pushState(null, document.title, location.href); window.addEventListener('popstate', function (event) { if (true){ history.pushState(null, document.title, location.href); c
Popstate事件
请帮助我们举一个例子,在这个例子中,我可以根据条件销毁Popstate事件
history.pushState(null, document.title, location.href);
window.addEventListener('popstate', function (event) {
if (true){
history.pushState(null, document.title, location.href);
console.log('Back Button Prevented');
} else {
window.removeEventListener('popstate', ()=> {
console.log('Go back');
}, true);
history.back();
}
});
传递给removeEventListener
的第二个参数必须是要删除的函数
您正在传递另一个函数,该函数尚未注册为事件处理程序,因此不会发生任何事情
将事件处理程序声明为具有可重用引用的函数。然后将该引用用于removeEventListener
和addEventListener
history.pushState(null, document.title, location.href);
function myEventListener (event) {
if (true){
history.pushState(null, document.title, location.href);
console.log('Back Button Prevented');
} else {
window.removeEventListener('popstate', myEventListener);
history.back();
}
}
window.addEventListener('popstate', myEventListener);
要删除侦听器,必须将侦听器函数本身传递给
removeEventListener()
代码中的另一个问题是,使用if(true)
,将永远无法到达正在删除侦听器的else
块。您可能需要在侦听器外部设置一个布尔变量,在第一次调用侦听器时更改该变量
var backButtonPrevented = false;
history.pushState(null, document.title, location.href);
function popStateListener(event) {
if (backButtonPrevented === false){
history.pushState(null, document.title, location.href);
console.log('Back Button Prevented');
backButtonPrevented = true;
} else {
window.removeEventListener('popstate', popStateListener);
history.back();
}
}
window.addEventListener('popstate', popStateListener);
他确实添加了一个例子,就在他的答案中。:)