You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用event.preventDefault()后,如何在SweetAlert确认后提交表单?

解决表单提交前SweetAlert确认后放行的问题

直接在用户确认的回调里调用表单元素的submit()方法即可,因为手动调用这个方法不会触发绑定的submit事件监听器,所以不会陷入循环提交的问题。

修改后的代码如下:

// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
    'use strict'

    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.querySelectorAll('.needs-validation')

    // Loop over them and prevent submission
    Array.prototype.slice.call(forms)
        .forEach(function(form) {
            form.addEventListener('submit', function(event) {

                if (!form.checkValidity()) {
                    event.preventDefault()
                    event.stopPropagation()
                } else {
                    event.preventDefault();
                    Swal.fire({
                        title: 'Are you sure?',
                        text: "You won't be able to revert this!",
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#3085d6',
                        cancelButtonColor: '#d33',
                        confirmButtonText: 'Yes, delete it!'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            // 手动提交表单
                            form.submit();
                        }
                    })

                }

                form.classList.add('was-validated')

            }, false)
        })
})()

补充说明

  • 当你通过event.preventDefault()阻止了默认提交行为后,表单不会自动提交,此时调用form.submit()会绕过之前绑定的submit事件监听,直接发起表单提交请求。
  • 如果用户点击取消按钮,SweetAlert会自动关闭,表单不会提交,符合预期逻辑。

内容的提问来源于stack exchange,提问作者Bikash Chowdhury

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 17:35:27