|
本文档旨在指导开发者使用 JavaScript 创建一个动态编码测验。我们将解决一个常见问题:如何正确更新问题和选项,避免在测验过程中重复显示相同的内容。通过逐步讲解和示例代码,你将学会如何使用计数器来追踪当前问题,并动态更新测验内容。 初始化测验数据首先,我们需要一个包含问题、选项和答案的 JavaScript 数组。每个元素都是一个对象,包含 question、choices 和 answer 属性。
- var quizQuestions = [
- {
- question: "What method would you use to create a DOM object Element?",
- choices: [".getAttribute()", ".createElement()", ".getElementById", ".setAttribute()"],
- answer: ".createElement()"
- },
- {
- question: "What are variables used for?",
- choices: ["Iterating over arrays", "Linking a JavaScript file to your html", "Storing data", "Performing specific tasks"],
- answer: "Storing data"
- },
- {
- question: "When declaring a function, what comes after the keyword 'function'?",
- choices: ["()", ";", "/", "++"],
- answer: "()"
- },
- {
- question: "What would you use if you wanted to execute a block of code a set number of times?",
- choices: ["While loop", "Math.random()", "For loop", "Switch statement"],
- answer: "For loop"
- },
- {
- question: "Using the word 'break' will stop the code execution inside the switch block.",
- choices: ["True", "False"],
- Answer: "True"
- }
- ];
复制代码 获取 DOM 元素接下来,我们需要获取页面上的相关 DOM 元素,例如问题显示区域、选项按钮等。
- var highScoresButtonEl = document.querySelector(".high-scores");
- var startQuizEl = document.querySelector(".quiz-button");
- var introTextEl = document.querySelector(".intro-text");
- var questionsEl = document.querySelector(".questions");
- var choicesEl = document.querySelector(".choices");
- var answerEl = document.querySelector(".answer")
- var timerEl = document.querySelector(".timer");
- var choicesListEl = document.createElement("ul");
- choicesListEl.setAttribute("class", "choices");
- choicesEl.appendChild(choicesListEl);
复制代码 初始化问题计数器这是解决问题的关键。我们需要一个变量来跟踪当前的问题索引。
- var currentQuestionIndex = 0;
复制代码 显示问题和选项现在,我们需要编写函数来显示问题和选项。关键在于使用 currentQuestionIndex 来访问 quizQuestions 数组中的正确元素。
- function displayQuestion() {
- questionsEl.textContent = quizQuestions[currentQuestionIndex].question;
- }
- function displayChoices() {
- choicesListEl.innerHTML = ""; // 清空之前的选项
- for (let i = 0; i < quizQuestions[currentQuestionIndex].choices.length; i++) {
- var li = document.createElement("li");
- li.textContent = quizQuestions[currentQuestionIndex].choices[i];
- li.setAttribute("data-index", i); // 存储选项索引
- li.addEventListener("click", checkAnswer); // 添加点击事件监听器
- choicesListEl.appendChild(li);
- }
- }
复制代码注意: - choicesListEl.innerHTML = ""; 用于在显示新问题之前清除旧的选项。
- li.setAttribute("data-index", i); 将选项的索引存储在 data-index 属性中,方便后续判断答案。
- li.addEventListener("click", checkAnswer); 为每个选项添加点击事件监听器,点击后调用 checkAnswer 函数。
检查答案并更新问题checkAnswer 函数用于检查用户选择的答案是否正确,并更新问题。
- function checkAnswer(event) {
- var selectedIndex = event.target.getAttribute("data-index");
- var selectedAnswer = quizQuestions[currentQuestionIndex].choices[selectedIndex];
- var correctAnswer = quizQuestions[currentQuestionIndex].answer;
- if (selectedAnswer === correctAnswer) {
- answerEl.textContent = "Correct!";
- } else {
- answerEl.textContent = "Incorrect!";
- // 在这里可以添加扣除时间的逻辑
- }
- currentQuestionIndex++; // 增加问题索引
- if (currentQuestionIndex < quizQuestions.length) {
- displayQuestion();
- displayChoices();
- } else {
- // 测验结束逻辑
- answerEl.textContent = "Quiz Complete!";
- }
- }
复制代码 启动测验最后,我们需要在点击“开始测验”按钮时启动测验。
- startQuizEl.addEventListener("click", function() {
- document.querySelector(".intro-text").style.visibility = "hidden";
- startQuizEl.style.visibility = "hidden";
- //startTimer(); // 启动计时器,需要自行实现
- displayQuestion();
- displayChoices();
- })
复制代码 完整代码示例
- <!DOCTYPE html>
- <html>
- <head>
- <title>Coding Quiz</title>
- </head>
- <body>
- <header>
- <ul>
- <li><button class="high-scores" id="high-scores">High Scores</button></li>
- <li class="timer"></li>
- </ul>
- </header>
- <main>
- <div class="intro-text">
- <h1>Timed Coding Quiz</h1>
- <p>Come test your coding knowledge with this timed coding quiz! Everytime you answer a questoin incorrectly,
- 8 seconds is deducted from your total time! Good luck!</p>
- </main>
- </div>
- <section class="quiz-content">
- <button class="quiz-button" id="quiz-button" type="submit">Start Quiz</button>
- <div class="questions" id="questions"></div>
- <div class="choices" id="choices"></div>
- <div class="answer" id="answer"></div>
- </section>
- <script>
- // Array of the questions, choices, and answers for the quiz.
- var quizQuestions = [
- {
- question: "What method would you use to create a DOM object Element?",
- choices: [".getAttribute()", ".createElement()", ".getElementById", ".setAttribute()"],
- answer: ".createElement()"
- },
- {
- question: "What are variables used for?",
- choices: ["Iterating over arrays", "Linking a JavaScript file to your html", "Storing data", "Performing specific tasks"],
- answer: "Storing data"
- },
- {
- question: "When declaring a function, what comes after the keyword 'function'?",
- choices: ["()", ";", "/", "++"],
- answer: "()"
- },
- {
- question: "What would you use if you wanted to execute a block of code a set number of times?",
- choices: ["While loop", "Math.random()", "For loop", "Switch statement"],
- answer: "For loop"
- },
- {
- question: "Using the word 'break' will stop the code execution inside the switch block.",
- choices: ["True", "False"],
- Answer: "True"
- }
- ];
- // Buttons
- var highScoresButtonEl = document.querySelector(".high-scores");
- var startQuizEl = document.querySelector(".quiz-button");
- var introTextEl = document.querySelector(".intro-text");
- var questionsEl = document.querySelector(".questions");
- var choicesEl = document.querySelector(".choices");
- var answerEl = document.querySelector(".answer")
- var timerEl = document.querySelector(".timer");
- var choicesListEl = document.createElement("ul");
- choicesListEl.setAttribute("class", "choices");
- choicesEl.appendChild(choicesListEl);
- var currentQuestionIndex = 0;
- function displayQuestion() {
- questionsEl.textContent = quizQuestions[currentQuestionIndex].question;
- }
- function displayChoices() {
- choicesListEl.innerHTML = ""; // Clear previous choices
- for (let i = 0; i < quizQuestions[currentQuestionIndex].choices.length; i++) {
- var li = document.createElement("li");
- li.textContent = quizQuestions[currentQuestionIndex].choices[i];
- li.setAttribute("data-index", i);
- li.addEventListener("click", checkAnswer);
- choicesListEl.appendChild(li);
- }
- }
- function checkAnswer(event) {
- var selectedIndex = event.target.getAttribute("data-index");
- var selectedAnswer = quizQuestions[currentQuestionIndex].choices[selectedIndex];
- var correctAnswer = quizQuestions[currentQuestionIndex].answer;
- if (selectedAnswer === correctAnswer) {
- answerEl.textContent = "Correct!";
- } else {
- answerEl.textContent = "Incorrect!";
- // Add time deduction logic here
- }
- currentQuestionIndex++;
- if (currentQuestionIndex < quizQuestions.length) {
- displayQuestion();
- displayChoices();
- } else {
- // Quiz complete logic
- answerEl.textContent = "Quiz Complete!";
- }
- }
- // Button that starts the timer, displays the first question and the first set of choices.
- startQuizEl.addEventListener("click", function() {
- document.querySelector(".intro-text").style.visibility = "hidden";
- startQuizEl.style.visibility = "hidden";
- //startTimer();
- displayQuestion();
- displayChoices();
- })
- </script>
- </body>
- </html>
复制代码 注意事项- 计时器: 上述代码中 startTimer() 函数需要你自行实现,用于实现测验的计时功能。
- 分数: 你可以添加一个变量来跟踪用户的分数,并在 checkAnswer 函数中根据答案是否正确来更新分数。
- 测验结束: 在 checkAnswer 函数中,当 currentQuestionIndex 大于等于 quizQuestions.length 时,表示测验结束。你需要添加相应的逻辑来显示最终分数、保存分数等。
- 错误处理: 为了提高代码的健壮性,可以添加错误处理机制,例如检查 quizQuestions 数组是否为空,或者处理用户点击选项时可能出现的异常。
总结通过使用计数器来跟踪当前问题,并动态更新问题和选项,我们可以创建一个功能完善的 JavaScript 编码测验。记住,关键在于正确地管理状态,并在每次用户回答问题后更新状态。希望这篇教程能够帮助你构建自己的测验应用程序!
道勤主机提供365天*24小时全年全天无休、实时在线、零等待的售后技术支持。竭力为您免费处理您在使用道勤主机过程中所遇到的一切问题!
如果您是道勤主机用户,那么您可以通过QQ【792472177】、售后QQ【59133755】、旺旺【诠释意念】、微信:q792472177免费电话、后台提交工单这些方式联系道勤主机客服!
如果您不是我们的客户也没问题,点击页面最右边的企业QQ在线咨询图标联系我们并购买后,我们为您免费进行无缝搬家服务,让您享受网站零访问延迟的迁移到道勤主机的服务! |