JavaScript选择题评分异常:选中正确答案仍显示0分求助
问题排查:JavaScript选择题始终返回0分的原因及修复方案
问题描述
实现的JavaScript选择题功能中,用户选择任意答案组合(包括全部正确答案)后,点击“Get Results”按钮,返回结果始终为“You got 0 out of 2 (0%) correct.”,无法正确计算得分。
错误根源分析
核心问题是索引不匹配:
- 页面加载时调用
generateContent函数,展示sampleData[currentIndex](初始值为0)的题目,但函数末尾会立即执行currentIndex++,导致currentIndex变为1; - 用户点击“Get Results”调用
checkAnswer时,代码会用当前的currentIndex(值为1)去获取sampleData[1]的正确答案,但用户实际选择的是sampleData[0]的题目选项,两者完全不匹配,因此得分始终为0; - 后续每次点击“Generate”按钮,
currentIndex都会提前递增,导致提交时对比的永远是下一组数据的答案。
修复方案
新增专门记录当前展示数据的变量displayedIndex,让currentIndex仅负责控制下一次生成的内容索引,避免索引混淆:
- 初始化时添加
displayedIndex变量,初始值为0; - 在
generateContent函数中,先将当前的currentIndex赋值给displayedIndex,再执行currentIndex的递增; - 修改
checkAnswer函数,全部使用displayedIndex获取当前展示题目的正确答案。
修改后的完整JavaScript代码
// Define variables let title = document.getElementById("title"); let bodytext = document.getElementById("bodytext"); let source = document.getElementById("source"); let quiz = document.getElementById("quiz"); let submitButton = document.getElementById("submit"); let results = document.getElementById("results"); let generateButton = document.getElementById("generate"); // Define sample data let sampleData = [ { title: "Sample Title 1", bodytext: "This is the first sample text.", source: "Source 1", quiz: [ { question: "What is the capital of France?", choices: ["New York", "Paris", "London", "Berlin"], answer: "Paris" }, { question: "What is the largest country in the world?", choices: ["Russia", "China", "India", "USA"], answer: "Russia" } ] }, { title: "Sample Title 2", bodytext: "This is the second sample text.", source: "Source 2", quiz: [ { question: "What is the largest planet in our solar system?", choices: ["Earth", "Mars", "Jupiter", "Venus"], answer: "Jupiter" }, { question: "What is the highest mountain in the world?", choices: ["Mount Everest", "K2", "Kangchenjunga", "Lhotse"], answer: "Mount Everest" } ] }, { title: "Sample Title 3", bodytext: "This is the third sample text.", source: "Source 3", quiz: [ { question: "How many colors are on the Spanish flag?", choices: ["One", "Two", "Three", "Four"], answer: "Three" }, { question: "What is the smallest planet in our solar system?", choices: ["Mercury", "Venus", "Mars", "Earth"], answer: "Mercury" } ] } ]; // Define event listeners generateButton.addEventListener("click", generateContent); submitButton.addEventListener("click", checkAnswer); // Initialize current index and displayed index let currentIndex = 0; let displayedIndex = 0; // 新增:记录当前展示的是哪组数据 // Function to generate content function generateContent() { // 先把当前要展示的索引赋值给displayedIndex displayedIndex = currentIndex; // Get the data object at the current index in the sample data array let data = sampleData[currentIndex]; // Update the DOM with the data title.textContent = data.title; bodytext.textContent = data.bodytext; source.textContent = "Source: " + data.source; // Generate the quiz HTML let quizHTML = ""; for (let i = 0; i < data.quiz.length; i++) { quizHTML += "<p>" + data.quiz[i].question + "</p>"; for (let j = 0; j < data.quiz[i].choices.length; j++) { quizHTML += "<label><input type='radio' name='answer" + i + "' value='" + data.quiz[i].choices[j] + "'> " + data.quiz[i].choices[j] + "</label><br>"; } } quiz.innerHTML = quizHTML; // Clear the results results.textContent = ""; // Increment the current index currentIndex++; // Reset the current index to 0 if we reach the end of the array if (currentIndex >= sampleData.length) { currentIndex = 0; } } // Function to check the answer function checkAnswer() { let selectedAnswers = []; // 使用displayedIndex获取当前展示的题目数据 for (let i = 0; i < sampleData[displayedIndex].quiz.length; i++) { let selectedAnswer = document.querySelector("input[name='answer" + i + "']:checked"); if (selectedAnswer === null) { results.textContent = "Please answer all questions."; return; } selectedAnswers.push(selectedAnswer.value.trim().toLowerCase()); } let correctAnswers = []; // 使用displayedIndex获取当前展示题目的正确答案 for (let i = 0; i < sampleData[displayedIndex].quiz.length; i++) { correctAnswers.push(sampleData[displayedIndex].quiz[i].answer.trim().toLowerCase()); } if (selectedAnswers.length !== correctAnswers.length) { results.textContent = "Please answer all questions."; return; } let numCorrect = 0; for (let i = 0; i < selectedAnswers.length; i++) { if (selectedAnswers[i] === correctAnswers[i]) { numCorrect++; } } let percentCorrect = (numCorrect / selectedAnswers.length) * 100; results.textContent = "You got " + numCorrect + " out of " + selectedAnswers.length + " (" + percentCorrect.toFixed(2) + "%) correct."; } // Call the generateContent() function when the page loads generateContent();
额外优化点
- 原代码中未使用的
currentQuizIndex变量可直接删除; - 结果文本补充完整的
correct.后缀,与问题描述中的提示保持一致。
内容的提问来源于stack exchange,提问作者user21505124
相关产品推荐
相关产品推荐

