JavaScript Trivia游戏:如何捕获按钮点击值并验证答案正确性
解决Trivia应用的答案校验问题
问题核心
之前的checkAnswer函数错误地获取了整个答案数组,而非用户点击的单个答案;改用addEventListener后,需要给按钮绑定对应答案数据,才能在点击时校验对错。
解决步骤及代码修改
1. 填充按钮时绑定对应答案对象
假设你已有随机生成试题的逻辑,在填充按钮文本的同时,把对应答案对象绑定到点击事件中:
// 全局变量存储当前随机试题 let randomQuestion; // 加载随机试题并填充按钮 function loadRandomQuestion() { // 随机获取试题(你已实现的逻辑) const randomIndex = Math.floor(Math.random() * questions.length); randomQuestion = questions[randomIndex]; // 获取所有答案按钮 const answerButtons = document.querySelectorAll('.answers-btn'); // 遍历按钮,填充文本并绑定点击事件 answerButtons.forEach((button, index) => { const currentAnswer = randomQuestion.answers[index]; button.textContent = currentAnswer.text; // 点击时传入当前答案对象 button.addEventListener('click', () => checkAnswer(currentAnswer)); }); }
2. 修改checkAnswer函数校验对错
直接使用传入的答案对象判断结果:
function checkAnswer(selectedAnswer) { if (selectedAnswer.correct) { console.log("Correct!"); } else { console.log("Incorrect"); } }
3. 页面初始化加载试题
页面加载完成后调用加载函数:
document.addEventListener('DOMContentLoaded', loadRandomQuestion);
补充:修正试题数组语法错误
你提供的questions数组中最后一个答案的引号混用,修正后:
export const questions = [ { question: 'What year did the United States gain independence?', answers: [ { text: '1776', correct: true }, { text: '1676', correct: false }, { text: '1576', correct: false }, { text: '1476', correct: false } ] }, // 其他试题... ]
关键说明
给每个按钮绑定点击事件时,直接传入对应answer对象,就能精准获取用户选择的答案,避免全局变量混乱,同时保证校验逻辑的准确性。
内容的提问来源于stack exchange,提问作者postmetric
相关产品推荐
相关产品推荐

