【问题标题】:Disable JS beforeunload if button with specific id has been clicked如果单击了具有特定 ID 的按钮,则在卸载前禁用 JS
【发布时间】:2018-10-10 16:54:43
【问题描述】:

问题:

我有一个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 的解决方案。

【问题讨论】:

    标签: javascript button onbeforeunload


    【解决方案1】:

    当他们按下按钮时移除事件监听器。为此,您需要使用命名函数而不是匿名函数,因此您可以在调用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);
    });

    【讨论】:

    • 我看不到buttonPushed 指的是什么?
    • 对不起,这是我之前版本的回答,我忘记删除了。
    • @Barmar 嗨,我会在 ie11 中看到一个弹出窗口,显示“无法获取未定义或空引用的属性 'addEventListener'”。
    • @Barmar 最后一行以document 开头。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 2022-07-29
    • 2021-06-04
    • 1970-01-01
    • 2014-11-02
    • 1970-01-01
    相关资源
    最近更新 更多