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

点击测验最后一题选项触发控制台错误的解决方法

解决测验网页最后一题点击报错问题

问题原因

点击最后一题选项时,原代码会将seq递增到超出数组最大索引的值(数组长度为5,索引范围0-4,seq会变成5),此时调用moreQA()尝试访问quesAns[5],因该位置不存在(值为undefined),读取其属性时触发cannot read properties of undefined错误。

解决方案

简化索引变量,调整点击事件逻辑:先判断当前题目的对错,再检查是否还有下一题,仅当存在下一题时才更新索引并加载新题目;最后一题点击后,终止题目的切换并做结束处理。

修改后的完整代码

const question = document.querySelector(".ques");
const first = document.querySelector(".first");
const second = document.querySelector(".second");
const third = document.querySelector(".third");
const fourth = document.querySelector(".fourth");
const answers = document.querySelectorAll(".ans");
const rightAnswer = document.querySelector(".right_ans");

// 合并seq和seq2为单个索引变量,初始指向第一题
let currentIndex = 0;

const quesAns = [
  {
    ques: "Who is the CEO of Google?",
    a: "A. Bill Gates",
    b: "B. Tim Cook",
    c: "C. Sundar Pichai",
    d: "D. Larry Page",
    true: "C. Sundar Pichai",
  },
  {
    ques: "Who is founder of Microsoft",
    a: "A. Elon Musk",
    b: "B. Steve Jobs",
    c: "C. Mark Jukerberg",
    d: "D. Bill Gates",
    true: "D. Bill Gates",
  },
  {
    ques: "Who is founder of Facebook?",
    a: "A. Mark Zukerberg",
    b: "B. Larry Page",
    c: "C. Satya Nadela",
    d: "D. Evan Spiegel",
    true: "A. Mark Zukerberg",
  },
  {
    ques: "Who is richest person in the world?",
    a: "A. Mark Zukerberg",
    b: "B. Elon Musk",
    c: "C. Bill gates",
    d: "D. Mukesh Ambani",
    true: "B. Elon Musk",
  },
  {
    ques: "What is responsible for styling in web page?",
    a: "HTML",
    b: "XML",
    c: "CSS",
    d: "JavaScript",
    true: "CSS",
  }
];

function moreQA() {
  const currentQues = quesAns[currentIndex];
  question.innerHTML = currentQues.ques;
  first.innerHTML = currentQues.a;
  second.innerHTML = currentQues.b;
  third.innerHTML = currentQues.c;
  fourth.innerHTML = currentQues.d;
}

answers.forEach((ans) => {
  ans.addEventListener("click", (e) => {
    const selectedAnswer = e.target.innerHTML.trim();
    const currentQues = quesAns[currentIndex];
    
    // 判断当前答案对错
    if (currentQues.true === selectedAnswer) {
      rightAnswer.innerHTML = "你的答案正确";
      rightAnswer.style.color = "green";
    } else {
      rightAnswer.innerHTML = "你的答案错误";
      rightAnswer.style.color = "red";
    }
    
    // 检查是否还有下一题
    if (currentIndex < quesAns.length - 1) {
      currentIndex++;
      moreQA();
    } else {
      // 最后一题处理:禁止继续点击,显示完成提示
      answers.forEach(el => el.style.pointerEvents = 'none');
      rightAnswer.innerHTML += "<br>测验已完成!";
    }
  });
});

// 初始化加载第一题
moreQA();

关键修改点

  • 合并seq和seq2为currentIndex,避免索引变量混乱。
  • 点击事件中先判断当前题目的对错,再检查是否存在下一题,仅当有下一题时才更新索引并加载新题目。
  • 最后一题点击后,通过pointerEvents: 'none'禁止选项继续点击,同时显示测验完成提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 22:35:03