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

如何将SweetAlert2弹窗中输入的文本传递到.then方法中?

问题根源

你的代码存在两个核心错误:

  • 声明的resetPassword函数接收的email形参没有实际作用,你没有从SweetAlert2的弹窗输入结果中获取用户输入的邮箱值,而是直接把未赋值的形参传给了Firebase接口
  • SweetAlert2的then回调返回的是结果对象,不是直接的输入内容,需要先判断用户是否点击了确认按钮,再从value字段中取出输入的邮箱

修复后代码

function resetPassword() {
    /* 点击忘记密码触发的弹窗逻辑 */
    Swal.fire({
        title: 'Enter the email address',
        input: 'email', // 改为email类型可自带邮箱格式校验,比text更合理
        inputAttributes: {
            autocapitalize: 'off'
        },
        showCancelButton: true,
        confirmButtonText: 'Send Reset Email',
        preConfirm: (email) => {
            // 新增非空校验
            if (!email) {
                Swal.showValidationMessage('Email address cannot be empty')
            }
            return email
        }
    }).then((result) => {
        // 先判断用户是否点击了确认按钮,避免取消操作也触发接口调用
        if (result.isConfirmed) {
            // 从result.value中获取用户输入的邮箱
            const inputEmail = result.value
            firebase.auth().sendPasswordResetEmail(inputEmail)
            .then(() => {
                Swal.fire({
                    title: 'Email Sent!',
                    text: 'Check your email for a reset link!',
                    icon: 'success', // 新版SweetAlert2用icon字段代替旧版的type字段,兼容旧版可保留type
                    confirmButtonText: 'Cool'
                });
            })
            .catch((error) => {
                Swal.fire({
                    title: 'Error!',
                    text: error.message,
                    icon: 'error',
                    confirmButtonText: 'Cool'
                });
            });
        }
    });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:39:03