2 回答

TA贡献2041条经验 获得超4个赞
为了删除监听器,您必须将监听器函数本身传递给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);

TA贡献1873条经验 获得超9个赞
传递给第二个参数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);
添加回答
举报