已尝试使用 Below Code 但它没有破坏 Popstate Event
。
请帮助我们完成示例,在该示例中我可以根据条件销毁 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()
。
代码中的另一个问题是,使用 if (true)
时,您将永远无法到达正在删除监听器的 else
block 。您可能想要做的是在监听器外部有一个 bool 变量,您在第一次调用监听器时更改它。
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);
关于javascript - 如何销毁 'Popstate' 事件监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55573728/