如果单击具有特定 id 的按钮,则在卸载之前禁用 JS
Disable JS beforeunload if button with specific id has been clicked
问题:
我有一个 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 的解决方案。
当他们按下按钮时删除事件侦听器。为此,您需要使用命名函数而不是匿名函数,以便在调用 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);
});