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

HTML中JS的if条件弹窗在prompt获取回答后无法触发求助

问题修复方案

你的代码核心问题是比较条件里的no没有加引号——prompt()返回的是字符串类型,你需要用字符串字面量"no"来和inquire做比较,直接写no会被JS当成未定义变量,导致条件判断完全失效。

修正后的代码

function contact() {
  let name = prompt("What is your full name?");
  let email = prompt("what is your email?");
  let inquire = prompt("Have you done yoga before?");
  // 用字符串"no"做比较,同时转小写兼容不同输入格式
  if (inquire.toLowerCase() === "no") {
    alert(`We're glad you chose us to start your journey ${name},we'll be in touch soon!`);
  } else {
    alert(`We can't wait to practice with you ${name}, we'll be in touch soon!`);
  }
}
let contactButton = document.querySelector(".contactButton");
contactButton.addEventListener("click", contact);

额外优化建议

  • 加入toLowerCase()可以兼容用户输入的No/NO等不同大小写形式,避免因为输入格式导致判断偏差
  • 可以增加空值判断,处理用户直接点击取消的情况,避免弹窗出现undefined:
    if (!name || !email) {
      alert("Please enter your name and email!");
      return;
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 22:03:11