首页 > 解决方案 > 如果单击了具有特定 ID 的按钮,则在卸载前禁用 JS

问题描述

问题:

beforeunload如果用户尝试离开网页,我会激活一个警告标志。如果用户按下特定按钮,我希望禁用此行为。

JS:

window.addEventListener("beforeunload", function (e) {
    var confirmationMessage = "Not a good idea - want to reconsider?";

    (e || window.event).returnValue = confirmationMessage; //Gecko + IE
    return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
});

HTML:

<a href="survey.php" class="btn btn-primary" id="initiatesurvey">Next</a>

期望的输出:

为了能够在没有激活 beforeunload 的情况下单击下一步按钮。我已经看到了一些关于 SO 的解决方案,但我正在寻找一个纯 JS 的解决方案。

标签: javascriptbuttononbeforeunload

解决方案


当他们按下按钮时移除事件监听器。为此,您需要使用命名函数而不是匿名函数,以便在调用时引用它removeEventListener

function beforeUnload(e) {
  var confirmationMessage = "Not a good idea - want to reconsider?";

  (e || window.event).returnValue = confirmationMessage; //Gecko + IE
  return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.

}

window.addEventListener("beforeunload", beforeUnload);

document.getElementById("initiatesurvey").addEventListener("click", function() {
  window.removeEventListener("beforeunload", beforeUnload);
});


推荐阅读