为了账号安全,请及时绑定邮箱和手机立即绑定

如何销毁“ Popstate”事件监听器?

如何销毁“ Popstate”事件监听器?

呼唤远方 2021-04-11 12:15:37
尝试了以下代码,但没有破坏Popstate Event。请帮助我们提供一个示例,其中我可以Popstate Event根据条件销毁该示例。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();  }});
查看完整描述

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);


查看完整回答
反对 回复 2021-04-22
?
眼眸繁星

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);


查看完整回答
反对 回复 2021-04-22
  • 2 回答
  • 0 关注
  • 811 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信