添加if-else后文本冒险游戏Enter键无响应问题解决
文本冒险游戏输入无响应问题修复
问题原因
- 代码语法错误:
game函数内部的else分支未编写任何逻辑,还把Enter键的事件监听代码错误嵌套在了game函数里,导致JS解析失败,事件监听根本没生效。 - Switch case语法误用:
case "walk to cave" || "walk north"这种写法不成立,逻辑运算符||在这里会直接返回第一个真值(也就是"walk to cave"),永远不会匹配第二个输入值。 - 输入框未清空:执行命令后输入框内容保留,影响后续输入体验。
修复后的完整代码
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width" /> <title>The Dungeon of Agkorak</title> </head> <body> <h2>"Welcome to the Dungeon of Agkorak!"</h2> <p id="output">You stand in a large open field, to the north there is a cave entrance in the side of a hill. <br>There is a mailbox there. <br>What do you do? </p> <input type="text" id="input" autofocus> <script> const output = document.getElementById("output"); const inputField = document.getElementById("input"); var room = 0 // 处理用户输入的函数 function game() { const input = inputField.value.toLowerCase(); // 清空输入框 inputField.value = ""; if (room === 0) { switch (input) { // 用多个case匹配同一逻辑 case "walk to cave": case "walk north": output.innerHTML = "You walk up from the field to the cave entrance"; room = 1; break; case "walk to mailbox": output.innerHTML = "you walk to the mailbox"; room = 1; break; default: output.innerHTML = "invalid command"; } } else if (room === 1) { switch (input) { case "enter cave": case "enter": output.innerHTML = "inside the cave you see painting on the wall"; room = 2; break; case "look around": output.innerHTML = "nothing of any real interest"; break; default: output.innerHTML = "invalid command"; } } // 可以在这里添加更多room的逻辑 } // 事件监听放在全局,不要嵌套在game函数里 inputField.addEventListener('keyup', function (event) { if (event.key === 'Enter') { game(); } }); </script> </body> </html>
关键修复点说明
- 调整代码结构:把Enter键的事件监听代码移到
game函数外部,确保页面加载时就能注册监听,同时删除多余的空else分支。 - 修正switch case写法:对于需要匹配多个输入值的情况,使用连续的
case语句,共用同一逻辑块。 - 添加输入框清空逻辑:执行
game函数后清空输入框,提升用户体验。
内容的提问来源于stack exchange,提问作者GanjaGatherer
相关产品推荐
相关产品推荐

