js实现答题
使用 JavaScript 实现答题功能
基本答题逻辑
创建题目数组,包含题目、选项和正确答案:
const questions = [
{
question: "JavaScript 是一种什么语言?",
options: ["标记语言", "脚本语言", "编译语言", "样式语言"],
answer: 1
},
{
question: "以下哪个不是 JavaScript 的数据类型?",
options: ["String", "Boolean", "Number", "Float"],
answer: 3
}
];
显示题目功能
实现题目显示和选项渲染:
let currentQuestion = 0;
let score = 0;
function showQuestion() {
const question = questions[currentQuestion];
document.getElementById('question').textContent = question.question;
const optionsContainer = document.getElementById('options');
optionsContainer.innerHTML = '';
question.options.forEach((option, index) => {
const button = document.createElement('button');
button.textContent = option;
button.onclick = () => checkAnswer(index);
optionsContainer.appendChild(button);
});
}
检查答案功能
验证用户选择并更新分数:
function checkAnswer(selectedIndex) {
const question = questions[currentQuestion];
if (selectedIndex === question.answer) {
score++;
alert('回答正确!');
} else {
alert(`回答错误!正确答案是:${question.options[question.answer]}`);
}
currentQuestion++;
if (currentQuestion < questions.length) {
showQuestion();
} else {
showResult();
}
}
显示结果功能
展示最终得分和答题统计:
function showResult() {
const quizContainer = document.getElementById('quiz-container');
quizContainer.innerHTML = `
<h2>答题完成!</h2>
<p>你的得分是:${score}/${questions.length}</p>
<p>正确率:${(score/questions.length*100).toFixed(2)}%</p>
<button onclick="location.reload()">重新答题</button>
`;
}
HTML 结构示例
配套的基础 HTML 结构:
<div id="quiz-container">
<h2 id="question"></h2>
<div id="options"></div>
<div id="result"></div>
</div>
进阶功能实现
添加计时器和题目类型判断:
let timeLeft = 30;
const timer = setInterval(() => {
timeLeft--;
document.getElementById('timer').textContent = `剩余时间:${timeLeft}秒`;
if (timeLeft <= 0) {
clearInterval(timer);
checkAnswer(-1); // 超时自动跳过
}
}, 1000);
随机题目功能
实现题目随机排序:
function shuffleQuestions() {
for (let i = questions.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[questions[i], questions[j]] = [questions[j], questions[i]];
}
}
本地存储功能
使用 localStorage 保存最高分:
function saveHighScore() {
const highScore = localStorage.getItem('highScore') || 0;
if (score > highScore) {
localStorage.setItem('highScore', score);
}
}
初始化函数
启动答题系统:

function initQuiz() {
shuffleQuestions();
showQuestion();
document.getElementById('timer').textContent = `剩余时间:${timeLeft}秒`;
}
这些代码片段组合起来可以构建一个完整的 JavaScript 答题系统,包含题目显示、答案验证、计时功能和成绩统计等核心功能。






