首页 > 解决方案 > 在“then”中显示验证消息,而不是自动关闭 Swal

问题描述

获取后是否可以在方法中关闭Sweetalert (2)?如果请求返回特定的内容,我只想让 Swal 保持打开状态,而不是打开一个全新的警报。在方法中执行验证消息时,它会显示片刻,但警报会自动关闭。thenpreConfirmSwal.showValidationMessage()then

有没有办法让警报保持打开状态?

标签: sweetalert2

解决方案


If I'm not mistaken, you should be calling the Swal.showValidationMessage() function inside the preConfirm() option, not in the then() promise return.

Would validating whatever input you're looking for inside the preConfirm() just work fine?

Example:

Swal.fire({
    title: "title",
    text: "text",
    icon: "info",
    showCancelButton: true,
    cancelButtonText: "Cancel",
    confirmButtonText: "Done!",
    html: `<input id="input1 class="swal2-input" />
           <input id="input2 class="swal2-input" />`,
    preConfirm: () => {
        let value1 = Swal.getPopup().querySelector('#input1').value;
        let value2 = Swal.getPopup().querySelector('#input2').value;

        if (value1 == somethingWrong1) {
            // Notify error and keep alert open.
            Swal.showValidationMessage('Invalid input #1.');

        } else if (value2 == somethingWrong2) {
            // Notify error and keep alert open.
            Swal.showValidationMessage('Invalid input #2.');

        } else {
            // Promise return value that will be available inside the 'then()'.
            // Alert will now close.
            return {
                input1: input1,
                input2: input2
            };
        }
    }
}).then((inputs) => {
    if (inputs !== "cancel") {
        // Access the inputs using: inputs.value.input1 and inputs.value.input2
        // And do whatever you want.
    }
});

推荐阅读