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

如何正确将Open Trivia API返回题目存入数组实现逐题展示

Trivia Game 题目存储与逐题交互实现方案

现有代码问题排查

  • 变量声明缺失:循环内的display_all_questions、current_question未使用let/const声明,会变成隐式全局变量,引发作用域异常
  • 渲染逻辑错误:for循环遍历题目时每次都直接覆盖题目容器的innerHTML,页面最终只会显示最后1道题,完全没有实现逐题展示的基础逻辑
  • 数组存储逻辑无效:虽然push操作本身能执行(你以为未生效本质是存完后没有配套的按序读取、渲染逻辑),但你没有记录当前题目的位置索引,存完数组后无法按顺序取题,而且存储时只存了题干,没有同步存储正确答案,后续无法判断用户答题是否正确
  • 缺少交互绑定逻辑:没有给True/False按钮绑定点击事件,用户答题后无法触发切题、判分的操作

修正后完整实现代码

首先提前准备好页面基础结构:

<div id="triviaQuestion"></div>
<button id="trueBtn">True</button>
<button id="falseBtn">False</button>
<div id="result"></div>

对应JS逻辑:

const api_url = "https://opentdb.com/api.php?amount=10&difficulty=easy&type=boolean";
const triviaQ = document.getElementById("triviaQuestion");
const trueBtn = document.getElementById("trueBtn");
const falseBtn = document.getElementById("falseBtn");
const resultBox = document.getElementById("result");
const question_array = [];
// 记录当前展示的题目索引,初始为第1题(索引0)
let currentQuestionIndex = 0;
// 记录用户得分
let score = 0;

async function getAPI(url) {
  const response = await fetch(url);
  const data = await response.json();
  saveQuestions(data.results);
  // 加载第一题
  renderQuestion();
}

// 把接口返回的所有题目存入数组
function saveQuestions(questionList) {
  questionList.forEach(item => {
    question_array.push({
      question: item.question,
      correctAnswer: item.correct_answer
    })
  })
}

// 渲染当前索引对应的题目
function renderQuestion() {
  // 所有题目答完时展示结果
  if (currentQuestionIndex >= question_array.length) {
    triviaQ.innerHTML = `答题结束!你的得分是${score}/${question_array.length}`;
    // 隐藏答题按钮
    trueBtn.style.display = 'none';
    falseBtn.style.display = 'none';
    return;
  }
  // 展示当前题目
  triviaQ.innerHTML = question_array[currentQuestionIndex].question;
  // 清空上一题的结果提示
  resultBox.innerHTML = '';
}

// 处理用户答题逻辑
function handleAnswer(userAnswer) {
  const currentQuestion = question_array[currentQuestionIndex];
  // 判断答案是否正确
  if (userAnswer === currentQuestion.correctAnswer) {
    score++;
    resultBox.innerHTML = '回答正确!';
  } else {
    resultBox.innerHTML = `回答错误!正确答案是${currentQuestion.correctAnswer}`;
  }
  // 索引+1,延迟500ms让用户看到答题结果后切下一题
  setTimeout(() => {
    currentQuestionIndex++;
    renderQuestion();
  }, 500)
}

// 给按钮绑定点击事件
trueBtn.addEventListener('click', () => handleAnswer('True'));
falseBtn.addEventListener('click', () => handleAnswer('False'));

// 页面加载时拉取题目
getAPI(api_url);

关键逻辑说明

  • 接口请求成功后,先遍历返回的results数组,把每道题的题干、正确答案统一存入question_array,不在存储循环里做DOM渲染操作
  • 用currentQuestionIndex变量记录当前正在展示的题目位置,初始值为0对应第一题
  • 单独抽离renderQuestion函数负责题目渲染,每次调用时根据当前索引取对应题目插入DOM,索引超过题目总长度时展示最终得分
  • 给两个答题按钮绑定点击事件,用户点击后传入选择的答案做判分,索引自增后重新调用渲染函数展示下一题,答完10题自动结束流程

内容的提问来源于stack exchange,提问作者Rebja A.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 02:27:14