Trivia应用题目迭代异常:仅函数首次运行时数组值更新求助
问题解决:Trivia答题应用题目无法迭代的问题
直接修复:调用pullQuestions()更新页面
你的submitA()函数只递增了question.id,但没有触发页面更新逻辑——也就是没有调用pullQuestions()。修改后的代码如下:
function submitA() { question.id++; // 新增:调用pullQuestions刷新题目内容 pullQuestions(); console.log("submitA() Run)", "Question ID: ", question.id, headerQ, content); }
修正错误的代码粘贴
你贴的Question Array部分实际是select1()函数,这明显是粘贴错误。正确的全局题目数组应该类似这样(示例):
// 全局题目数组 const question = [ { headerQ: "Question 1", content: "示例题目内容1" }, { headerQ: "Question 2", content: "示例题目内容2" }, { headerQ: "Question 3", content: "示例题目内容3" } ]; // 给数组添加id属性追踪当前题目索引 question.id = 0;
优化代码:简化pullQuestions()逻辑
当前pullQuestions()用多个if判断索引的写法冗余且扩展性差,直接用question.id作为数组索引即可,还能增加越界判断防止报错:
function pullQuestions() { // 检查当前索引是否在数组有效范围内 if (question.id >= 0 && question.id < question.length) { const currentQ = question[question.id]; document.getElementById("headerQ").innerHTML = currentQ.headerQ; document.getElementById("content").innerHTML = currentQ.content; console.log("pullQuestions() Executed"); console.log("Variables: ", "headerQ = ", headerQ, "content = ", content); } else { // 所有题目完成后的处理,比如显示结束界面 console.log("所有题目已完成!"); document.getElementById("gameArea").style.display = "none"; // 可在此添加显示结果或重新开始的逻辑 } }
更规范的写法:单独追踪题目索引
不建议给数组添加自定义的id属性,单独用一个变量追踪当前索引更符合JavaScript规范:
// 全局变量:当前题目索引 let currentQIndex = 0; // 全局题目数组 const questions = [ { headerQ: "Question 1", content: "示例题目内容1" }, { headerQ: "Question 2", content: "示例题目内容2" }, { headerQ: "Question 3", content: "示例题目内容3" } ];
对应的函数修改:
function startGame(){ document.getElementById("startArea").style.display = "none"; document.getElementById("gameArea").style.display = "block"; currentQIndex = 0; pullQuestions(); console.log("startgame() Executed", currentQIndex); console.log(questions[0], questions[1]); } function submitA() { currentQIndex++; pullQuestions(); console.log("submitA() Run)", "Question Index: ", currentQIndex, headerQ, content); } function pullQuestions() { if (currentQIndex >= 0 && currentQIndex < questions.length) { const currentQ = questions[currentQIndex]; document.getElementById("headerQ").innerHTML = currentQ.headerQ; document.getElementById("content").innerHTML = currentQ.content; console.log("pullQuestions() Executed"); console.log("Variables: ", "headerQ = ", headerQ, "content = ", content); } else { console.log("所有题目已完成!"); document.getElementById("gameArea").style.display = "none"; } }
内容的提问来源于stack exchange,提问作者user17949142
相关产品推荐
相关产品推荐

