且构网

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

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

更新时间:2023-12-01 20:02:34

我建议捕获表单的提交事件,然后删除 confirmExit 来自 onbeforeunload 事件绑定的功能或设置一个标志以指示可以提交页面。例如:

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.