CS50 Trivia项目自由回答模块正确答案无响应问题求助
问题解决:CS50 Trivia自由回答无响应问题
你的代码核心问题是变量名拼写错误:在提交按钮的点击事件处理函数中,正确答案分支里把input误写成了intput,导致JavaScript执行时抛出错误,因此输入正确答案时没有任何反馈。
修复后的完整代码
<!DOCTYPE html> <html lang="en"> <head> <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet"> <link href="styles.css" rel="stylesheet"> <title>Trivia!</title> <script> document.addEventListener('DOMContentLoaded', function(){ let incorrect = document.querySelectorAll(".incorrect"); let correct = document.querySelector("#correct"); let response = document.querySelector("#response"); correct.addEventListener('click', function(){ correct.style.backgroundColor = "green"; response.innerHTML = "Correct"; }) for (let x = 0; x < incorrect.length; x++) { incorrect[x].addEventListener('click', function() { incorrect[x].style.backgroundColor = 'red'; response.innerHTML = "incorrect"; }) } document.querySelector("#submit").addEventListener('click', function(){ let input = document.querySelector('input'); let reply = document.querySelector("#reply"); if (input.value.toLowerCase() === "poseidon") { input.style.color = 'green'; reply.innerHTML = "correct"; } else { input.style.color = "red"; reply.innerHTML = "incorrect"; } }); }); </script> </head> <body> <div class="header"> <h1>Trivia!</h1> </div> <div class="container"> <div class="section"> <h2>Part 1: Multiple Choice </h2> <hr> <h3>What is the capital of New York?</h3> <button class="incorrect">Manhattan</button> <button class="incorrect">Bronx</button> <button id="correct">Albany</button> <p id="response"></p> </div> <div class="section"> <h2>Part 2: Free Response</h2> <hr> <h3>Who was the first god killed in the game title God of War III</h3> <input type="text"> <button id="submit">Submit</button> <p id="reply"></p> </div> </div> </body> </html>
额外优化建议
- 大小写不敏感判断:使用
input.value.toLowerCase() === "poseidon",用户输入Poseidon或POSEIDON也能判定正确,提升体验。 - 更清晰的视觉反馈:可以把修改文字色改为修改输入框边框色,比如
input.style.borderColor = 'green',反馈更直观。 - 状态重置:每次提交前清空之前的样式,避免残留的颜色影响下一次输入判断。
内容的提问来源于stack exchange,提问作者jbgame463
相关产品推荐
相关产品推荐

