You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JSON文件实现JavaScript单选答题器并存储答案到LocalStorage

动态生成单选答题并保存答案到LocalStorage

1. 先确认你的JSON数据结构

假设你的JSON文件(比如questions.json)结构如下,每个题目包含唯一ID、题干、选项列表:

[
  {
    "id": "q1",
    "question": "以下哪个不是JavaScript基本数据类型?",
    "options": [
      { "value": "string", "text": "字符串" },
      { "value": "number", "text": "数字" },
      { "value": "array", "text": "数组" },
      { "value": "boolean", "text": "布尔值" }
    ]
  },
  // 另外3道题结构类似...
]

2. HTML基础结构

只需要一个容器来承载动态生成的题目:

<div id="quiz-container"></div>

3. JavaScript核心实现

3.1 加载JSON数据并生成答题区域

用fetch加载本地JSON文件,循环生成每个题目的DOM元素:

const quizContainer = document.getElementById('quiz-container');

// 加载题目数据
async function loadQuestions() {
  try {
    const response = await fetch('questions.json');
    const questions = await response.json();
    
    // 遍历每个题目生成DOM
    questions.forEach(question => {
      // 创建题目容器
      const questionDiv = document.createElement('div');
      questionDiv.className = 'question-item';
      questionDiv.dataset.questionId = question.id;
      
      // 添加题干
      const questionTitle = document.createElement('h3');
      questionTitle.textContent = `${question.id.slice(1)}. ${question.question}`;
      questionDiv.appendChild(questionTitle);
      
      // 创建选项容器
      const optionsDiv = document.createElement('div');
      optionsDiv.className = 'options';
      
      // 遍历选项生成单选框和标签
      question.options.forEach(option => {
        const optionLabel = document.createElement('label');
        optionLabel.className = 'option-label';
        
        const radioInput = document.createElement('input');
        radioInput.type = 'radio';
        radioInput.name = `question-${question.id}`;
        radioInput.value = option.value;
        
        // 加载时恢复之前的选择
        const savedAnswers = JSON.parse(localStorage.getItem('quizAnswers')) || {};
        if (savedAnswers[question.id] === option.value) {
          radioInput.checked = true;
        }
        
        // 监听选择事件,保存答案到LocalStorage
        radioInput.addEventListener('change', () => saveAnswer(question.id, option.value));
        
        const optionText = document.createElement('span');
        optionText.textContent = option.text;
        
        optionLabel.appendChild(radioInput);
        optionLabel.appendChild(optionText);
        optionsDiv.appendChild(optionLabel);
      });
      
      questionDiv.appendChild(optionsDiv);
      quizContainer.appendChild(questionDiv);
    });
  } catch (error) {
    console.error('加载题目失败:', error);
    quizContainer.textContent = '题目加载失败,请检查JSON文件路径';
  }
}

// 页面加载时执行
document.addEventListener('DOMContentLoaded', loadQuestions);

3.2 保存答案到LocalStorage的函数

把选中的答案以键值对形式存在LocalStorage,键是题目ID,值是选项值:

function saveAnswer(questionId, selectedValue) {
  // 先取出已保存的答案,没有则为空对象
  let savedAnswers = JSON.parse(localStorage.getItem('quizAnswers')) || {};
  // 更新当前题目的答案
  savedAnswers[questionId] = selectedValue;
  // 存回LocalStorage
  localStorage.setItem('quizAnswers', JSON.stringify(savedAnswers));
}

4. 额外提示

  • 确保JSON文件路径正确,如果和HTML在同一目录,直接写文件名即可;如果在子目录,要写相对路径(比如./data/questions.json)。
  • 可以给答题区域加一些CSS样式,提升用户体验:
.question-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 8px;
}
.option-label {
  display: block;
  margin: 8px 0;
  cursor: pointer;
}
.option-label input:checked + span {
  color: #2196F3;
  font-weight: bold;
}

内容的提问来源于stack exchange,提问作者petar komadina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:57:25