0

0

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

霞舞

霞舞

发布时间:2025-09-15 17:20:12

|

251人浏览过

|

来源于php中文网

原创

使用 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);

初始化问题计数器

这是解决问题的关键。我们需要一个变量来跟踪当前的问题索引。

立即学习Java免费学习笔记(深入)”;

var currentQuestionIndex = 0;

显示问题和选项

现在,我们需要编写函数来显示问题和选项。关键在于使用 currentQuestionIndex 来访问 quizQuestions 数组中的正确元素。

Cutout.Pro
Cutout.Pro

AI驱动的视觉设计平台

下载
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 编码测验。记住,关键在于正确地管理状态,并在每次用户回答问题后更新状态。希望这篇教程能够帮助你构建自己的测验应用程序!

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

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

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

954

2023.09.19

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

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

4356

2024.08.14

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

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

4356

2024.08.14

li是什么元素
li是什么元素

li是HTML标记语言中的一个元素,用于创建列表。li代表列表项,它是ul或ol的子元素,li标签的作用是定义列表中的每个项目。本专题为大家li元素相关的各种文章、以及下载和课程。

438

2023.08.03

TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

49

2026.03.13

Python异步编程与Asyncio高并发应用实践
Python异步编程与Asyncio高并发应用实践

本专题围绕 Python 异步编程模型展开,深入讲解 Asyncio 框架的核心原理与应用实践。内容包括事件循环机制、协程任务调度、异步 IO 处理以及并发任务管理策略。通过构建高并发网络请求与异步数据处理案例,帮助开发者掌握 Python 在高并发场景中的高效开发方法,并提升系统资源利用率与整体运行性能。

88

2026.03.12

C# ASP.NET Core微服务架构与API网关实践
C# ASP.NET Core微服务架构与API网关实践

本专题围绕 C# 在现代后端架构中的微服务实践展开,系统讲解基于 ASP.NET Core 构建可扩展服务体系的核心方法。内容涵盖服务拆分策略、RESTful API 设计、服务间通信、API 网关统一入口管理以及服务治理机制。通过真实项目案例,帮助开发者掌握构建高可用微服务系统的关键技术,提高系统的可扩展性与维护效率。

272

2026.03.11

Go高并发任务调度与Goroutine池化实践
Go高并发任务调度与Goroutine池化实践

本专题围绕 Go 语言在高并发任务处理场景中的实践展开,系统讲解 Goroutine 调度模型、Channel 通信机制以及并发控制策略。内容包括任务队列设计、Goroutine 池化管理、资源限制控制以及并发任务的性能优化方法。通过实际案例演示,帮助开发者构建稳定高效的 Go 并发任务处理系统,提高系统在高负载环境下的处理能力与稳定性。

59

2026.03.10

Kotlin Android模块化架构与组件化开发实践
Kotlin Android模块化架构与组件化开发实践

本专题围绕 Kotlin 在 Android 应用开发中的架构实践展开,重点讲解模块化设计与组件化开发的实现思路。内容包括项目模块拆分策略、公共组件封装、依赖管理优化、路由通信机制以及大型项目的工程化管理方法。通过真实项目案例分析,帮助开发者构建结构清晰、易扩展且维护成本低的 Android 应用架构体系,提升团队协作效率与项目迭代速度。

99

2026.03.09

热门下载

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

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
React 教程
React 教程

共58课时 | 6.1万人学习

TypeScript 教程
TypeScript 教程

共19课时 | 3.5万人学习

Bootstrap 5教程
Bootstrap 5教程

共46课时 | 3.6万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号