js实现考试
实现考试系统的JavaScript方案
创建考试题目数据结构
使用数组存储题目信息,每个题目包含题干、选项和正确答案:
const questions = [
{
question: "JavaScript中哪个关键字用于声明变量?",
options: ["var", "let", "const", "全部正确"],
answer: 3
},
{
question: "以下哪个方法可以添加数组元素?",
options: ["push()", "pop()", "shift()", "unshift()"],
answer: 0
}
];
构建考试界面
通过DOM操作动态生成考试界面:
function renderExam() {
const examContainer = document.getElementById('exam-container');
questions.forEach((q, index) => {
const questionDiv = document.createElement('div');
questionDiv.innerHTML = `
<h3>题目 ${index + 1}: ${q.question}</h3>
${q.options.map((opt, i) => `
<label>
<input type="radio" name="q${index}" value="${i}">
${opt}
</label><br>
`).join('')}
`;
examContainer.appendChild(questionDiv);
});
}
实现计分功能
提交时计算得分并显示结果:
function calculateScore() {
let score = 0;
questions.forEach((q, index) => {
const selectedOption = document.querySelector(`input[name="q${index}"]:checked`);
if (selectedOption && parseInt(selectedOption.value) === q.answer) {
score++;
}
});
alert(`您的得分: ${score}/${questions.length}`);
}
添加计时功能
使用定时器实现考试倒计时:
let timeLeft = 1800; // 30分钟
function startTimer() {
const timer = setInterval(() => {
timeLeft--;
document.getElementById('timer').textContent =
`${Math.floor(timeLeft/60)}:${timeLeft%60 < 10 ? '0' : ''}${timeLeft%60}`;
if (timeLeft <= 0) {
clearInterval(timer);
calculateScore();
}
}, 1000);
}
防止页面刷新
监听beforeunload事件防止意外退出:

window.addEventListener('beforeunload', (e) => {
e.preventDefault();
return e.returnValue = '考试尚未提交,确定要离开吗?';
});
完整实现流程
- HTML结构包含考试容器和提交按钮
- 页面加载时调用renderExam()和startTimer()
- 提交按钮绑定calculateScore事件
- 添加CSS样式优化界面显示效果
这种实现方案支持题型扩展、自动评分和时间控制等核心考试功能,可根据需求进一步增加题目随机排序、错题回顾等功能模块。






