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

如何在JavaScript的if语句中验证文本 解决promo码匹配不生效问题

问题根因

  • 你声明的优惠码输入框DOM变量为txtPromo,但判断逻辑中直接使用了未定义的promo变量,且没有读取输入框的value属性获取用户输入内容,导致判断条件永远不成立,直接触发else分支
  • 登录逻辑中调用的Firebase Auth方法名拼写错误,正确驼峰命名为signInWithEmailAndPassword,全小写的方法不存在会触发运行报错

修复后代码

// 获取页面元素
const txtEmail = document.getElementById('email');
const txtPassword = document.getElementById('password');
const btnLogin = document.getElementById('btnlogin');
const btnSignUp = document.getElementById('btnsignup');
const btnLogout = document.getElementById('btnsignout');
const txtPromo = document.getElementById('promo');

// 绑定登录事件
btnLogin.addEventListener('click', e => {
  console.log("已触发登录");
  // 获取邮箱和密码
  const email = txtEmail.value;
  const password = txtPassword.value;
  const auth = firebase.auth();
  // 修复方法名拼写错误
  const promise = auth.signInWithEmailAndPassword(email,password);
  promise.catch(e => console.log(e.message));
});

// 绑定注册事件
btnSignUp.addEventListener('click', e => {
  // 新增:获取优惠码输入值,去除首尾空格避免用户输入空格导致匹配失败
  const promo = txtPromo.value.trim();
  if (promo === "dog") {
    alert("账号已创建,请登录");      
    console.log("账号已创建");
    // 获取邮箱和密码
    const email = txtEmail.value;
    const password = txtPassword.value;
    const auth = firebase.auth();
    console.log(email);
    console.log(password);
    auth.createUserWithEmailAndPassword(email, password)
    .then((userCredential) => {
      // 注册成功
      var user = userCredential.user;
      console.log(user);
      window.location.href = "login.html";
    })
    .catch((error) => {
      var errorCode = error.code;
      var errorMessage = error.message;
      console.log(errorMessage);
    });
  } else {
    alert("请输入优惠码"); 
    console.log("需要优惠码")
  };
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 02:24:00