在选择题交互式学习体验的设计中,main.js 文件扮演着至关重要的角色。它负责处理用户的输入,验证答案,并提供即时的反馈。以下是一篇详细的指南,将帮助您理解如何使用 JavaScript 来编写一个简单而有效的选择题交互式学习体验。
1. 准备工作
在开始之前,确保您有以下准备工作:
- HTML 文件:用于构建用户界面。
- CSS 文件(可选):用于美化界面。
- JavaScript 文件(即
main.js):用于添加交互功能。
HTML 示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>选择题交互式学习体验</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="quiz-container">
<div id="question"></div>
<ul id="answers"></ul>
<button id="submit-btn">提交答案</button>
<div id="feedback"></div>
</div>
<script src="main.js"></script>
</body>
</html>
CSS 示例(styles.css)
#quiz-container {
width: 80%;
margin: auto;
text-align: center;
}
#answers li {
list-style-type: none;
margin: 10px 0;
}
#feedback {
margin-top: 20px;
}
2. 编写 JavaScript
在 main.js 文件中,我们将实现以下功能:
- 显示问题。
- 显示选项。
- 用户选择答案并提交。
- 验证答案并显示反馈。
JavaScript 示例(main.js)
// 问题数据
const questions = [
{
question: "JavaScript 是什么?",
options: ["一种编程语言", "一种数据库", "一种操作系统"],
answer: "一种编程语言"
},
// 添加更多问题...
];
// 当前问题的索引
let currentQuestionIndex = 0;
// 显示当前问题的函数
function showQuestion() {
const question = questions[currentQuestionIndex];
document.getElementById('question').textContent = question.question;
const answersElement = document.getElementById('answers');
answersElement.innerHTML = ''; // 清空选项
question.options.forEach(option => {
const li = document.createElement('li');
li.textContent = option;
li.onclick = () => selectOption(option);
answersElement.appendChild(li);
});
}
// 用户选择答案的函数
function selectOption(selected) {
document.querySelectorAll('#answers li').forEach(li => {
li.style.backgroundColor = '';
});
document.querySelector(`#answers li:contains('${selected}')`).style.backgroundColor = 'lightgreen';
}
// 用户提交答案的函数
function submitAnswer() {
const selected = document.querySelector('#answers li.active');
if (selected) {
const isCorrect = selected.textContent === questions[currentQuestionIndex].answer;
document.getElementById('feedback').textContent = isCorrect ? '正确!' : '错误,再试一次。';
currentQuestionIndex++;
if (currentQuestionIndex < questions.length) {
showQuestion();
} else {
document.getElementById('submit-btn').disabled = true;
document.getElementById('feedback').textContent = '所有问题已完成!';
}
}
}
// 初始化函数
function init() {
showQuestion();
document.getElementById('submit-btn').addEventListener('click', submitAnswer);
}
// 页面加载完成时执行初始化函数
window.onload = init;
3. 运行和测试
将上述代码保存为 index.html、styles.css 和 main.js 文件。在浏览器中打开 index.html 文件,您应该能够看到一个交互式的问题和选项列表。选择一个选项并点击提交按钮,您将看到相应的反馈。
通过这种方式,您可以使用 main.js 来创建一个简单而有效的交互式学习体验。根据需要,您可以扩展此示例,添加更多的问题、选项和样式。
