HTML+JS文本冒险游戏按钮触发非预期函数问题求助
代码问题汇总
- 全局变量
currentQuestion没有初始值,页面加载后无法显示第一个问题 - 所有多条件判断写法错误:
|| "xxx"的写法逻辑永远返回真,比如value == "Yes" || "yes",等价于(value == "Yes") || Boolean("yes"),而非空字符串的布尔值永远为真,导致条件判断完全失效,永远进入第一个匹配的分支,这是你遇到触发时机错误的核心原因 - 点击事件绑定错误:一是属性名拼写错误,将
onclick写为onlclick;二是绑定事件时直接调用函数(加了括号)或者给函数名加了引号,导致事件绑定失败,函数会立即执行而非点击后触发 - 分支逻辑未补全:匹配到正确输入后,没有更新页面内容、也没有绑定后续阶段的处理函数
修正后代码
HTML代码
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>repl.it</title> <link href="style.css" rel="stylesheet" type="text/css"/> <script src="script.js"></script> </head> <body onload="init()"> <center> <h1 class="Title"> Text Adventure HTML </h1> <h5> 请严格按照问题下方给出的选项格式输入答案 </h5> <br><br> </center> <p id="currentQuestion"></p> <p id="givenAnswers"></p> <input type="text" id="answer" placeholder="在这里输入你的答案"> <input id="enter" type="button" onclick="wakeUp()" value="确定"> </body> </html>
JS代码
var answers = "Yes<br>No" // 初始化第一个问题 var currentQuestion = "你醒了吗?" var name = "" function init(){ document.getElementById("currentQuestion").innerHTML = currentQuestion document.getElementById("givenAnswers").innerHTML = answers } function wakeUp(){ let inputVal = document.getElementById("answer").value.trim() if(inputVal == "No" || inputVal == "no" ){ currentQuestion = "你没有醒过来,游戏结束,请刷新页面重启" answers = "" document.getElementById("answer").value = "" init() document.getElementById("enter").onclick = dead } else if(inputVal == "Yes" || inputVal == "yes" ){ currentQuestion = "OLD MAN: 早上好,你感觉怎么样?" answers = "Good<br>Bad<br>Else" document.getElementById("answer").value = "" init() // 绑定下一个阶段的处理函数 document.getElementById("enter").onclick = howUFeel } else{ // 输入不匹配清空输入框 document.getElementById("answer").value = "" } } function dead(){ currentQuestion = "你已经死亡,请刷新页面重启" document.getElementById("currentQuestion").innerHTML = currentQuestion document.getElementById("answer").value = "" } function howUFeel(){ let inputVal = document.getElementById("answer").value.trim() if (inputVal == "else" || inputVal == "Else" ){ currentQuestion = "你说的else是什么意思?愿意详细说说吗?" answers = "No" document.getElementById("answer").value = "" init() } else if(inputVal == "good" || inputVal == "Good" ){ currentQuestion = "OLD MAN: thats good to hear, whats your name?" answers = "直接输入你的名字即可" document.getElementById("answer").value = "" init() // 后续需要接收名字的话,可以在这里绑定对应的处理函数 // document.getElementById("enter").onclick = 你写的接收名字的函数名 } else if(inputVal == "bad" || inputVal == "Bad"){ // 可自行补全选bad的分支逻辑 currentQuestion = "OLD MAN: 听到这个我很遗憾,先好好休息吧" answers = "" document.getElementById("answer").value = "" init() } else{ document.getElementById("answer").value = "" } }
内容的提问来源于stack exchange,提问作者Tman06er
相关产品推荐
相关产品推荐

