javascript - 如果单击了具有特定 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 的解决方案。
解决方案
当他们按下按钮时移除事件监听器。为此,您需要使用命名函数而不是匿名函数,以便在调用时引用它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);
});
推荐阅读
- java - 更改 Maven 主路径
- url - 如何将 url 链接添加到 WinWheel.js 图像切片?
- python - 单个队列上的多处理
- c++ - 从 QT 5.12.8 迁移到 5.15.2 MOC 失败
- mysql - sql 在“查询中”重复查询但比查询中的一次要快?
- reactjs - 如何在一个类中调用 2 个 api 以便两者都工作?(反应)
- python - 将方法从一个类复制到另一个(python)
- sql-server - 必须在 nopcommerce 4.3 中声明存储过程的标量变量错误
- python - 记录用户提供的输入值和执行 GUI 时调用的函数
- javascript - react-globe.gl 显示 geojson 文件的扭曲版本