使用 JavaScript 创建动态编码测验:逐步指南

酷丽同学_2671

酷丽同学_2671

2025-09-15

271人浏览

原创

使用 javascript 创建动态编码测验:逐步指南

本文档旨在指导开发者使用 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 数组中的正确元素。

Java 接口排错助手
Java 接口排错助手

在调试 Java 后端 API 故障时使用此技能,尤其适用于以下任务:分析日志、跨 Controller、Service 和 Mapper 层追踪请求、定位异常根因、检查 SQL 执行或参数流转,以及生成简洁的诊断结论与修复方案。

下载
function displayQuestion() {
    questionsEl.textContent = quizQuestions[currentQuestionIndex].question;
}

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

    for (let i = 0; i <p>注意:</p>
  • 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 <h3>启动测验</h3><p>最后,我们需要在点击“开始测验”按钮时启动测验。</p><pre class="brush:php;toolbar:false;">startQuizEl.addEventListener("click", function() {
    document.querySelector(".intro-text").style.visibility = "hidden";
    startQuizEl.style.visibility = "hidden";
    //startTimer(); // 启动计时器,需要自行实现
    displayQuestion();
    displayChoices();
})

完整代码示例



    <title>Coding Quiz</title><header><ul>
<li><button class="high-scores" id="high-scores">High Scores</button></li>
            <li class="timer">
        </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>
    
    </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></main>

注意事项

  • 计时器: 上述代码中 startTimer() 函数需要你自行实现,用于实现测验的计时功能。
  • 分数: 你可以添加一个变量来跟踪用户的分数,并在 checkAnswer 函数中根据答案是否正确来更新分数。
  • 测验结束: 在 checkAnswer 函数中,当 currentQuestionIndex 大于等于 quizQuestions.length 时,表示测验结束。你需要添加相应的逻辑来显示最终分数、保存分数等。
  • 错误处理: 为了提高代码的健壮性,可以添加错误处理机制,例如检查 quizQuestions 数组是否为空,或者处理用户点击选项时可能出现的异常。

总结

通过使用计数器来跟踪当前问题,并动态更新问题和选项,我们可以创建一个功能完善的 JavaScript 编码测验。记住,关键在于正确地管理状态,并在每次用户回答问题后更新状态。希望这篇教程能够帮助你构建自己的测验应用程序!

Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南

相关文章

PHP速学视频免费教程(入门到精通)
PHP速学视频免费教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
length函数用法
length函数用法

length函数用于返回指定字符串的字符数或字节数。可以用于计算字符串的长度,以便在查询和处理字符串数据时进行操作和判断。 需要注意的是length函数计算的是字符串的字符数,而不是字节数。对于多字节字符集,一个字符可能由多个字节组成。因此,length函数在计算字符串长度时会将多字节字符作为一个字符来计算。更多关于length函数的用法,大家可以阅读本专题下面的文章。

2023.09.19

1927

6

DOM是什么意思
DOM是什么意思

dom的英文全称是documentobjectmodel,表示文件对象模型,是w3c组织推荐的处理可扩展置标语言的标准编程接口;dom是html文档的内存中对象表示,它提供了使用javascript与网页交互的方式。想了解更多的相关内容,可以阅读本专题下面的文章。

2024.08.14

6541

7

Vite 项目如何打包和部署
Vite 项目如何打包和部署

Vite项目打包部署专题汇集生产构建、产物预览、输出目录、资源路径、Nginx与GitHub Pages部署及常见白屏和路由404问题的已审核文章,帮助读者完成上线流程。

2026.10.28

60

16

Vite 如何搭配 Vue.js
Vite 如何搭配 Vue.js

Vite搭配Vue.js专题汇集创建Vue 3项目、配置开发环境、路径别名、Vue插件、代理、多环境构建与调试的已审核文章,帮助读者完成从初始化到日常开发的配置。

2026.10.28

40

15

Vite 项目目录怎么看
Vite 项目目录怎么看

Vite项目目录专题汇集入口文件、src源码、public静态资源、路径别名、项目根目录和构建输出目录相关的已审核文章,帮助读者理解各文件夹的用途与引用方式。

2026.10.28

140

10

Gradle插件开发入门教程
Gradle插件开发入门教程

本专题介绍Gradle插件开发的基本流程,涵盖插件类编写、自定义任务注册、扩展参数设计和插件应用方法,帮助你理解插件如何组织构建逻辑,减少多个项目之间的重复配置。

2026.10.22

140

11

Gradle Wrapper配置教程
Gradle Wrapper配置教程

本专题介绍Gradle Wrapper的基本作用,涵盖文件组成、生成方法、版本配置和任务调用,帮助你理解项目如何使用指定的Gradle版本,减少不同开发环境带来的构建差异。

2026.10.22

120

10

Golangci-lint检查器使用教程
Golangci-lint检查器使用教程

本专题整理Golangci-lint常用Linters的用途与配置方法,覆盖错误处理、无效代码、安全、复杂度、命名和依赖检查,帮助项目合理选规则。

2026.10.22

80

15

Gradle怎么构建Java项目
Gradle怎么构建Java项目

本专题介绍Gradle Java项目构建方法,涵盖Java插件配置、依赖声明、源码编译、测试执行和打包检查,帮助你理解各阶段的任务关系,逐步完成项目构建。

2026.10.22

40

10

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
WebStorm 官方调试文档
WebStorm 官方调试文档

共0课时 | 0人学习

React 教程
React 教程

共58课时 | 12.4万人学习

TypeScript 教程
TypeScript 教程

共19课时 | 6.8万人学习