JS猜生日小游戏猜对日期后替换问号为图标不生效如何解决?
问题原因
- 变量作用域错误:
guessMonth、guessDay分别是月份检查、日期检查按钮点击回调函数的局部变量,全局作用域无法访问,你写在全局的胜利判断语句读取的两个值均为undefined,永远无法满足条件。 - 执行时机错误:全局的胜利判断仅在页面初次加载时执行1次,后续用户输入猜测值点击检查按钮时,不会重新触发该判断逻辑。
修复方案
- 在全局作用域声明两个变量,存储用户输入的月份和日期猜测值
- 每次用户点击月份检查或者日期检查按钮时,都触发一次胜利条件判断,满足条件就替换
#victory的内容 - 重置按钮点击时,要把
#victory的内容恢复为问号,同时重新生成随机日期
修改后完整JS代码
let secretMonth = Math.trunc(Math.random() * 12) + 1; let secretDay = Math.trunc(Math.random() * 31) + 1; // 全局存储用户的猜测值 let userGuessMonth = null; let userGuessDay = null; console.log(secretMonth, secretDay); // 封装胜利判断函数,复用逻辑 function checkVictory() { if (userGuessMonth === secretMonth && userGuessDay === secretDay) { // 这里如果要替换为图标库的爱心,直接把💖换成对应图标标签即可,比如Font Awesome的<i class="fa-solid fa-heart"></i> document.getElementById("victory").innerHTML = "💖"; } } document.querySelector(".btn-month").addEventListener("click", function () { const guessMonth = Number(document.querySelector(".guess-month").value); userGuessMonth = guessMonth; // 存储到全局变量 if (guessMonth === secretMonth) { document.querySelector(".hint-month").textContent = `You got the month right.`; document.querySelector(".left").style.backgroundColor = "blue"; } else if (guessMonth >= secretMonth) { document.querySelector(".hint-month").textContent = `Go lower.`; document.querySelector(".left").style.backgroundColor = "#d9480f"; } else { document.querySelector(".hint-month").textContent = `Go higher.`; document.querySelector(".left").style.backgroundColor = "#d9480f"; } // 每次检查完月份就判断是否胜利 checkVictory(); }); document.querySelector(".btn-day").addEventListener("click", function () { const guessDay = Number(document.querySelector(".guess-day").value); userGuessDay = guessDay; // 存储到全局变量 if (guessDay === secretDay) { document.querySelector(".hint-day").textContent = `You got the day right.`; document.querySelector(".right").style.backgroundColor = "blue"; } else if (guessDay >= secretDay) { document.querySelector(".hint-day").textContent = `Go lower.`; document.querySelector(".right").style.backgroundColor = "#d9480f"; } else { document.querySelector(".hint-day").textContent = `Go higher.`; document.querySelector(".right").style.backgroundColor = "#d9480f"; } // 每次检查完日期就判断是否胜利 checkVictory(); }); document.querySelector(".btn-reset").addEventListener("click", function () { // 重置全局猜测值 userGuessMonth = null; userGuessDay = null; // 恢复问号显示 document.getElementById("victory").innerHTML = "?"; document.querySelector(".hint-day").textContent = ""; document.querySelector(".hint-month").textContent = ""; document.querySelector(".right").style.backgroundColor = "#d9480f"; document.querySelector(".left").style.backgroundColor = "#d9480f"; document.querySelector(".guess-month").value = ""; document.querySelector(".guess-day").value = ""; // 重新生成随机日期 secretMonth = Math.trunc(Math.random() * 12) + 1; secretDay = Math.trunc(Math.random() * 31) + 1; console.log(secretMonth, secretDay); });
内容的提问来源于stack exchange,提问作者TomDev
相关产品推荐
相关产品推荐

