立即注册 找回密码

QQ登录

只需一步,快速开始

豆包只能上面
查看: 732|回复: 0

使用 JavaScript 创建动态编码测验的具体方法

[复制链接]

160

主题

0

回帖

2383

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2383
发表于 2025-9-15 18:01:20 | 显示全部楼层 |阅读模式
道勤网-数据www.daoqin.net
本文档旨在指导开发者使用 JavaScript 创建一个动态编码测验。我们将解决一个常见问题:如何正确更新问题和选项,避免在测验过程中重复显示相同的内容。通过逐步讲解和示例代码,你将学会如何使用计数器来追踪当前问题,并动态更新测验内容。
初始化测验数据
首先,我们需要一个包含问题、选项和答案的 JavaScript 数组。每个元素都是一个对象,包含 question、choices 和 answer 属性。
  1. var quizQuestions = [
  2.     {
  3.         question: "What method would you use to create a DOM object Element?",
  4.         choices: [".getAttribute()", ".createElement()", ".getElementById", ".setAttribute()"],
  5.         answer: ".createElement()"
  6.     },
  7.     {
  8.         question: "What are variables used for?",
  9.         choices: ["Iterating over arrays", "Linking a JavaScript file to your html", "Storing data", "Performing specific tasks"],
  10.         answer: "Storing data"
  11.     },
  12.     {
  13.         question: "When declaring a function, what comes after the keyword 'function'?",
  14.         choices: ["()", ";", "/", "++"],
  15.         answer: "()"
  16.     },
  17.     {
  18.         question: "What would you use if you wanted to execute a block of code a set number of times?",
  19.         choices: ["While loop", "Math.random()", "For loop", "Switch statement"],
  20.         answer: "For loop"
  21.     },
  22.     {
  23.         question: "Using the word 'break' will stop the code execution inside the switch block.",
  24.         choices: ["True", "False"],
  25.         Answer: "True"
  26.     }
  27. ];
复制代码
获取 DOM 元素
接下来,我们需要获取页面上的相关 DOM 元素,例如问题显示区域、选项按钮等。
  1. var highScoresButtonEl = document.querySelector(".high-scores");
  2. var startQuizEl = document.querySelector(".quiz-button");
  3. var introTextEl = document.querySelector(".intro-text");
  4. var questionsEl = document.querySelector(".questions");
  5. var choicesEl = document.querySelector(".choices");
  6. var answerEl = document.querySelector(".answer")
  7. var timerEl = document.querySelector(".timer");

  8. var choicesListEl = document.createElement("ul");
  9.     choicesListEl.setAttribute("class", "choices");
  10.     choicesEl.appendChild(choicesListEl);
复制代码
初始化问题计数器
这是解决问题的关键。我们需要一个变量来跟踪当前的问题索引。
  1. var currentQuestionIndex = 0;
复制代码
显示问题和选项
现在,我们需要编写函数来显示问题和选项。关键在于使用 currentQuestionIndex 来访问 quizQuestions 数组中的正确元素。
  1. function displayQuestion() {
  2.     questionsEl.textContent = quizQuestions[currentQuestionIndex].question;
  3. }

  4. function displayChoices() {
  5.     choicesListEl.innerHTML = ""; // 清空之前的选项

  6.     for (let i = 0; i < quizQuestions[currentQuestionIndex].choices.length; i++) {
  7.         var li = document.createElement("li");
  8.         li.textContent = quizQuestions[currentQuestionIndex].choices[i];
  9.         li.setAttribute("data-index", i); // 存储选项索引
  10.         li.addEventListener("click", checkAnswer); // 添加点击事件监听器
  11.         choicesListEl.appendChild(li);
  12.     }
  13. }
复制代码
注意:
  • choicesListEl.innerHTML = ""; 用于在显示新问题之前清除旧的选项。
  • li.setAttribute("data-index", i); 将选项的索引存储在 data-index 属性中,方便后续判断答案。
  • li.addEventListener("click", checkAnswer); 为每个选项添加点击事件监听器,点击后调用 checkAnswer 函数。
检查答案并更新问题
checkAnswer 函数用于检查用户选择的答案是否正确,并更新问题。
  1. function checkAnswer(event) {
  2.     var selectedIndex = event.target.getAttribute("data-index");
  3.     var selectedAnswer = quizQuestions[currentQuestionIndex].choices[selectedIndex];
  4.     var correctAnswer = quizQuestions[currentQuestionIndex].answer;

  5.     if (selectedAnswer === correctAnswer) {
  6.         answerEl.textContent = "Correct!";
  7.     } else {
  8.         answerEl.textContent = "Incorrect!";
  9.         // 在这里可以添加扣除时间的逻辑
  10.     }

  11.     currentQuestionIndex++; // 增加问题索引

  12.     if (currentQuestionIndex < quizQuestions.length) {
  13.         displayQuestion();
  14.         displayChoices();
  15.     } else {
  16.         // 测验结束逻辑
  17.         answerEl.textContent = "Quiz Complete!";
  18.     }
  19. }
复制代码
启动测验
最后,我们需要在点击“开始测验”按钮时启动测验。
  1. startQuizEl.addEventListener("click", function() {
  2.     document.querySelector(".intro-text").style.visibility = "hidden";
  3.     startQuizEl.style.visibility = "hidden";
  4.     //startTimer(); // 启动计时器,需要自行实现
  5.     displayQuestion();
  6.     displayChoices();
  7. })
复制代码
完整代码示例
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <title>Coding Quiz</title>
  5. </head>
  6. <body>
  7.     <header>
  8.         <ul>
  9.             <li><button class="high-scores" id="high-scores">High Scores</button></li>
  10.             <li class="timer"></li>
  11.         </ul>
  12.     </header>
  13.     <main>
  14.         <div class="intro-text">
  15.             <h1>Timed Coding Quiz</h1>
  16.             <p>Come test your coding knowledge with this timed coding quiz! Everytime you answer a questoin incorrectly,
  17.                 8 seconds is deducted from your total time! Good luck!</p>
  18.     </main>
  19.     </div>
  20.     <section class="quiz-content">
  21.         <button class="quiz-button" id="quiz-button" type="submit">Start Quiz</button>
  22.         <div class="questions" id="questions"></div>
  23.         <div class="choices" id="choices"></div>
  24.         <div class="answer" id="answer"></div>
  25.     </section>

  26.     <script>
  27.         // Array of the questions, choices, and answers for the quiz.
  28.         var quizQuestions = [
  29.             {
  30.                 question: "What method would you use to create a DOM object Element?",
  31.                 choices: [".getAttribute()", ".createElement()", ".getElementById", ".setAttribute()"],
  32.                 answer: ".createElement()"
  33.             },
  34.             {
  35.                 question: "What are variables used for?",
  36.                 choices: ["Iterating over arrays", "Linking a JavaScript file to your html", "Storing data", "Performing specific tasks"],
  37.                 answer: "Storing data"
  38.             },
  39.             {
  40.                 question: "When declaring a function, what comes after the keyword 'function'?",
  41.                 choices: ["()", ";", "/", "++"],
  42.                 answer: "()"
  43.             },
  44.             {
  45.                 question: "What would you use if you wanted to execute a block of code a set number of times?",
  46.                 choices: ["While loop", "Math.random()", "For loop", "Switch statement"],
  47.                 answer: "For loop"
  48.             },
  49.             {
  50.                 question: "Using the word 'break' will stop the code execution inside the switch block.",
  51.                 choices: ["True", "False"],
  52.                 Answer: "True"
  53.             }
  54.         ];

  55.         // Buttons
  56.         var highScoresButtonEl = document.querySelector(".high-scores");
  57.         var startQuizEl = document.querySelector(".quiz-button");

  58.         var introTextEl = document.querySelector(".intro-text");
  59.         var questionsEl = document.querySelector(".questions");
  60.         var choicesEl = document.querySelector(".choices");
  61.         var answerEl = document.querySelector(".answer")
  62.         var timerEl = document.querySelector(".timer");

  63.         var choicesListEl = document.createElement("ul");
  64.             choicesListEl.setAttribute("class", "choices");
  65.             choicesEl.appendChild(choicesListEl);

  66.         var currentQuestionIndex = 0;

  67.         function displayQuestion() {
  68.             questionsEl.textContent = quizQuestions[currentQuestionIndex].question;
  69.         }

  70.         function displayChoices() {
  71.             choicesListEl.innerHTML = ""; // Clear previous choices

  72.             for (let i = 0; i < quizQuestions[currentQuestionIndex].choices.length; i++) {
  73.                 var li = document.createElement("li");
  74.                 li.textContent = quizQuestions[currentQuestionIndex].choices[i];
  75.                 li.setAttribute("data-index", i);
  76.                 li.addEventListener("click", checkAnswer);
  77.                 choicesListEl.appendChild(li);
  78.             }
  79.         }

  80.         function checkAnswer(event) {
  81.             var selectedIndex = event.target.getAttribute("data-index");
  82.             var selectedAnswer = quizQuestions[currentQuestionIndex].choices[selectedIndex];
  83.             var correctAnswer = quizQuestions[currentQuestionIndex].answer;

  84.             if (selectedAnswer === correctAnswer) {
  85.                 answerEl.textContent = "Correct!";
  86.             } else {
  87.                 answerEl.textContent = "Incorrect!";
  88.                 // Add time deduction logic here
  89.             }

  90.             currentQuestionIndex++;

  91.             if (currentQuestionIndex < quizQuestions.length) {
  92.                 displayQuestion();
  93.                 displayChoices();
  94.             } else {
  95.                 // Quiz complete logic
  96.                 answerEl.textContent = "Quiz Complete!";
  97.             }
  98.         }


  99.         // Button that starts the timer, displays the first question and the first set of choices.
  100.         startQuizEl.addEventListener("click", function() {
  101.             document.querySelector(".intro-text").style.visibility = "hidden";
  102.             startQuizEl.style.visibility = "hidden";
  103.             //startTimer();
  104.             displayQuestion();
  105.             displayChoices();

  106.         })
  107.     </script>
  108. </body>
  109. </html>
复制代码
注意事项
  • 计时器: 上述代码中 startTimer() 函数需要你自行实现,用于实现测验的计时功能。
  • 分数: 你可以添加一个变量来跟踪用户的分数,并在 checkAnswer 函数中根据答案是否正确来更新分数。
  • 测验结束: 在 checkAnswer 函数中,当 currentQuestionIndex 大于等于 quizQuestions.length 时,表示测验结束。你需要添加相应的逻辑来显示最终分数、保存分数等。
  • 错误处理: 为了提高代码的健壮性,可以添加错误处理机制,例如检查 quizQuestions 数组是否为空,或者处理用户点击选项时可能出现的异常。
总结
通过使用计数器来跟踪当前问题,并动态更新问题和选项,我们可以创建一个功能完善的 JavaScript 编码测验。记住,关键在于正确地管理状态,并在每次用户回答问题后更新状态。希望这篇教程能够帮助你构建自己的测验应用程序!

道勤主机提供365天*24小时全年全天无休、实时在线、零等待的售后技术支持。竭力为您免费处理您在使用道勤主机过程中所遇到的一切问题! 如果您是道勤主机用户,那么您可以通过QQ【792472177】、售后QQ【59133755】、旺旺【诠释意念】、微信:q792472177免费电话、后台提交工单这些方式联系道勤主机客服! 如果您不是我们的客户也没问题,点击页面最右边的企业QQ在线咨询图标联系我们并购买后,我们为您免费进行无缝搬家服务,让您享受网站零访问延迟的迁移到道勤主机的服务!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

道勤网- 推荐内容!上一条 /2 下一条

!jz_fbzt! !jz_sgzt! !jz_xgzt! 快速回复 !jz_fhlb! !jz_lxwm! !jz_gfqqq!

关于我们|手机版|小黑屋|地图|【道勤网】-www.daoqin.net 软件视频自学教程|免费教程|自学电脑|3D教程|平面教程|影视动画教程|办公教程|机械设计教程|网站设计教程 ( 皖ICP备15000319号-1 )

GMT+8, 2026-10-11 04:35

Powered by DaoQin! X3.4 © 2016-2063 Dao Qin & 道勤科技

快速回复 返回顶部 返回列表