如何使用纯原生JavaScript开发具备题目切换与分数统计功能的迷你问答应用
Hey there! Let's tackle this vanilla JavaScript quiz feature step by step—since you already have the HTML/CSS in place, we'll focus on making the logic work smoothly. I'll break each part down with code that integrates right into your setup.
We need a clean way to store questions, options, and correct answers. An array of objects is perfect for this—each object holds all the info for one question:
// Define your quiz questions here (add as many as you want!) const quizQuestions = [ { question: "What is the correct syntax for linking an external JS file?", options: ["<script href='app.js'>", "<script name='app.js'>", "<script src='app.js'>", "<script file='app.js'>"], correctAnswer: 2 // Index of the correct option (zero-based) }, { question: "Which method adds an element to the END of an array?", options: ["shift()", "unshift()", "push()", "pop()"], correctAnswer: 2 }, { question: "What does 'DOM' stand for?", options: ["Document Object Model", "Data Object Model", "Document Oriented Model", "Data Oriented Model"], correctAnswer: 0 } ];
We need to track where we are in the quiz and the user's score, plus grab references to the HTML elements we'll manipulate:
// Track quiz state let currentQuestionIndex = 0; let score = 0; // Grab DOM elements (match these IDs to your existing HTML!) const questionText = document.getElementById('question-text'); const optionsContainer = document.getElementById('options-container'); const scoreDisplay = document.getElementById('score-display'); const nextBtn = document.getElementById('next-btn');
This function will render the current question and its options to the page, and add click handlers to each option:
function loadCurrentQuestion() { // Reset the options container and disable the next button first optionsContainer.innerHTML = ''; nextBtn.disabled = true; const currentQuestion = quizQuestions[currentQuestionIndex]; // Update the question text questionText.textContent = currentQuestion.question; // Create a button for each option currentQuestion.options.forEach((option, index) => { const optionBtn = document.createElement('button'); optionBtn.textContent = option; optionBtn.classList.add('option-btn'); // Use your existing CSS class for options // Add click event to check if the answer is correct optionBtn.addEventListener('click', () => checkAnswer(index)); optionsContainer.appendChild(optionBtn); }); }
When a user clicks an option, this function will verify if it's correct, update the score, and give visual feedback:
function checkAnswer(selectedIndex) { const currentQuestion = quizQuestions[currentQuestionIndex]; const allOptionBtns = optionsContainer.querySelectorAll('.option-btn'); // Disable all option buttons after selection so users can't change their answer allOptionBtns.forEach(btn => btn.disabled = true); if (selectedIndex === currentQuestion.correctAnswer) { // Correct answer: increment score and style the button green score++; scoreDisplay.textContent = score; allOptionBtns[selectedIndex].style.backgroundColor = '#4CAF50'; } else { // Wrong answer: mark selected red, and show the correct answer in green allOptionBtns[selectedIndex].style.backgroundColor = '#f44336'; allOptionBtns[currentQuestion.correctAnswer].style.backgroundColor = '#4CAF50'; } // Enable the next button once an answer is selected nextBtn.disabled = false; }
This function handles moving to the next question, or showing the final score when the quiz ends:
function goToNextQuestion() { currentQuestionIndex++; if (currentQuestionIndex < quizQuestions.length) { // Load the next question if there are more left loadCurrentQuestion(); } else { // Quiz is done: show final score and a restart option const quizContainer = document.querySelector('.quiz-container'); // Match your container class quizContainer.innerHTML = ` <h2>Quiz Completed!</h2> <p>Your final score: ${score}/${quizQuestions.length}</p> <button onclick="resetQuiz()">Restart Quiz</button> `; } } // Optional: Add a reset function to start the quiz over function resetQuiz() { currentQuestionIndex = 0; score = 0; scoreDisplay.textContent = score; loadCurrentQuestion(); }
Finally, kick off the quiz when the page loads, and wire up the next button:
// Start the quiz when the page finishes loading document.addEventListener('DOMContentLoaded', () => { loadCurrentQuestion(); nextBtn.addEventListener('click', goToNextQuestion); });
Quick Notes for Your Setup:
- Make sure your HTML has elements with the IDs used above (
question-text,options-container,score-display,next-btn). - Customize the CSS for
.option-btnto match your design (padding, margin, cursor, etc.). - You can tweak the feedback colors or add animations to make the quiz feel more interactive.
内容的提问来源于stack exchange,提问作者Ekedegba Benedict

