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

JS开发答题测验功能时单题显示所有选项的原因排查

问题根源

代码存在两处核心逻辑错误,直接导致所有题目选项堆叠在单个问题下:

  • 单题DOM的创建逻辑全部写在了题目遍历循环的外部,整个函数运行时只会生成1个题干元素、1个选项容器,后续遍历所有题目生成选项按钮时,都会把按钮追加到这唯一的选项容器中,不会为其他题目生成独立的题干和选项容器。
  • 题干赋值逻辑在循环外执行,只会读取初始currentQuestion对应的那道题的题干,所有题目的选项最终都挂在这道题的题干下方。
  • 额外隐患:正误提示的footer容器也写在了循环外,所有题目共用同一个提示元素,后续做答题交互时会出现提示错乱的问题。
修复方法

把单道题对应的所有DOM元素(题干、选项容器、提示footer)的创建逻辑,全部移动到题目遍历循环的内部,每遍历一道题就生成一套独立的DOM节点,不要在循环外提前创建单套节点复用。
如果要实现逐题展示、答完切题的效果,可以直接去掉外层的题目遍历循环,仅维护currentQuestion作为当前题序号,每次初始化/切题时先清空容器,再渲染当前序号对应的单道题即可。

核心修复代码参考:

var renderQuestions = function () {
  // 初始化当前题序号,避免重复渲染时序号溢出
  let currentQuestion = 0;

  // 逐题遍历,为每道题生成独立DOM
  for (let i = 0; i < quizQuestions.length; i++) {
    // 生成当前题的独立容器
    const questionsDiv = document.createElement("div");
    questionsDiv.className = "questions-div";

    // 生成当前题的题干
    const questionStem = document.createElement("h2");
    questionStem.className = "question-stem";
    questionStem.innerText = quizQuestions[currentQuestion].question;
    questionsDiv.append(questionStem);

    // 生成当前题的选项容器
    const answerOptionsDiv = document.createElement("div");

    // 生成当前题的正误提示footer
    const footerDiv = document.createElement("div");
    footerDiv.className = "footer-div";
    const footerTextCorrect = document.createElement("h2");
    footerTextCorrect.className = "footer-text-correct";
    footerTextCorrect.innerText = "Correct!";
    footerDiv.append(footerTextCorrect);
    const footerTextWrong = document.createElement("h2");
    footerTextWrong.className = "footer-text-wrong";
    footerTextWrong.innerText = "Wrong!";
    footerDiv.append(footerTextWrong);

    // 把当前题的所有节点挂载到全局容器
    questionsContainer.append(questionsDiv);
    questionsContainer.append(footerDiv);
    questionsDiv.append(answerOptionsDiv);

    // 仅生成当前题的4个选项按钮
    for (let j = 1; j <= 4; j++) {
      const optionBtn = document.createElement("button");
      const optionText = quizQuestions[currentQuestion].options[`${j}`];
      optionBtn.innerText = `${j}. ${optionText}`;
      optionBtn.addEventListener("click", selectAnswer);
      optionBtn.id = optionText;
      answerOptionsDiv.append(optionBtn);
    }

    currentQuestion++;
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 00:12:25