且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

离开页面时Js弹出但提交表单时不弹出

更新时间:2023-12-01 20:06:28

我建议捕获表单的提交事件,然后从 onbeforeunload中删除 confirmExit 函数> 事件绑定或者设置一个标志来表示页面可以提交.例如:

I would suggest capturing the submit event for the form and then either removing the confirmExit function from your onbeforeunload event binding or setting a flag to indicate that the page can be submitted. For example:

<script type="text/javascript">

    // Define flag to determine if the page can be left without confirmation
    var safeToLeave = false;

    // Handle user leaving the page
    function handleExit () {
        if (!safeToLeave) {
            return 'Si vous quittez ou actualisez la page, vous perdrez votre tutoriel';
        }
    }

    // Handle the user submitting the page form
    function handleSubmission() {
        safeToLeave = true;
    }

    // Bind to on evemts
    window.onbeforeunload = handleExit;
    document.getElementById('#my-form').onsubmit = handleSubmission;

</script>

我建议您通常考虑使用 addEventListener 方法来绑定事件,但是鉴于您的示例,我试图保持我的答案一致.

I'd recommend you consider using the addEventListener method for binding events in general, however given your example I've tried to keep my answer consistent.