首页 > 解决方案 > 无法阻止甜蜜警报关闭

问题描述

我试图email在关闭之前验证该字段,SweetAlert但由于某种原因,SweetAlert在捕获错误后正在关闭:

Swal.fire({
    title: title,
    html: template,
    preConfirm: function (email) {
        email = '';
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                if (email === '') {
                    alert("err");
                    reject('err')
                } else {
                    resolve()
                }
            }, 1000)
        }).catch(err => alert("error catched"))
    },
});

当错误被捕获时,我能做些什么来防止SweetAlert模式关闭?

谢谢

标签: javascriptjquerysweetalert2

解决方案


这是一个功能齐全的示例(用于解决您的特定问题):

<html>
    <body>
        <div class="showDialogButton">Show dialog</div>

        <script src="https://code.jquery.com/jquery-3.4.1.js"
            integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
            crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@8"></script>
        <script type="text/javascript">

            $(() => {

                const title = "Hi"
                const template = `<b>hello</b> world`

                $(".showDialogButton").click(() => {
                    Swal.fire({
                        title: title,
                        html: template,
                        preConfirm: function (email) {
                            email = '';
                            return new Promise(function (resolve, reject) {
                                setTimeout(function () {
                                    if (email === '') {

                                        reject('Email is empty!')

                                    } else {

                                        resolve()
                                    }
                                }, 1000)
                            }).catch(err => {
                                alert(`error: ${err}`)
                                return false
                            })
                        },
                    });
                })
            })
        </script>
    </body>
</html>

默认行为是关闭对话框。为了覆盖它,您必须false从您传入的函数返回.catch.

来自https://sweetalert2.github.io/#configuration

参数:preConfirm

默认值:空

说明:confirm前要执行的函数,可以是async(Promise-returning)也可以是sync。返回(或解析)的值可以是:

  • false防止弹出窗口关闭
  • 任何其他将该值作为result.valueof传递的Swal.fire()
  • undefined保持默认result.value

推荐阅读