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

尝试了以下代码,但没有破坏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();

  }

});


呼唤远方
浏览 812回答 2
2回答

缥缈止盈

为了删除监听器,您必须将监听器函数本身传递给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);

眼眸繁星

传递给第二个参数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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript