【问题标题】:Disable beforeunload when submitting a form with pure JS? [duplicate]用纯JS提交表单时禁用beforeunload? [复制]
【发布时间】:2020-01-23 20:58:21
【问题描述】:

如何在不使用任何第三方库(例如 jQuery)的情况下,在提交表单时禁用 onbeforeunload 事件?

我有:

HTML:

<form id="confirm_form">
    <input id="confirm_btn" type="submit" value="Confirm Action">
</form>

JS:

function onLeave() {
    return "Are you sure you wish to leave without performing the action?";
}
window.onbeforeunload = onLeave;

这个问题不是 How to disable beforeunload action when user is submitting a form?window.onbeforeunload - Only show warning when not submitting form 的重复问题,因为它们专门处理 jQuery。

【问题讨论】:

    标签: javascript onbeforeunload


    【解决方案1】:
    document.getElementById("confirm_form").addEventListener("submit", function() {
        window.onbeforeunload = null;
    });
    

    或者,如果您想对页面中的每个表单都执行此操作:

    function remove_onbeforeunload() {
        window.onbeforeunload = null;
    }
    let forms = document.getElementsByTagName("form");
    for(let i = 0; i < forms.length; i++) {
        forms.item(i).addEventListener("submit", remove_onbeforeunload);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-26
      • 1970-01-01
      • 1970-01-01
      • 2016-04-03
      • 1970-01-01
      • 2018-06-30
      • 1970-01-01
      相关资源
      最近更新 更多