
本文档旨在指导开发者使用 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 元素,例如问题显示区域、选项按钮等。
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);这是解决问题的关键。我们需要一个变量来跟踪当前的问题索引。
立即学习“Java免费学习笔记(深入)”;
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);
}
}注意:
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>通过使用计数器来跟踪当前问题,并动态更新问题和选项,我们可以创建一个功能完善的 JavaScript 编码测验。记住,关键在于正确地管理状态,并在每次用户回答问题后更新状态。希望这篇教程能够帮助你构建自己的测验应用程序!
以上就是使用 JavaScript 创建动态编码测验:逐步指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号