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
相关产品推荐
相关产品推荐

