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

如何无需硬编码遍历唯一ID,实现Quiz按钮绑定对应题目

问题:循环绑定按钮与对应测验题目

我正在制作一个Quiz(测验),希望点击不同按钮时展示对应的题目。但每个按钮都有唯一ID,难以在循环中动态切换ID名称来绑定对应题目(如myBtn1对应questions[0],myBtn2对应questions[1]等)。现有代码如下:

现有代码

JavaScript

let mybtn1 = document.getElementById("myBtn1")
let questions = [
    {
        question : "What is an Epidemics?",
        choiceA : "CorrectA",
        choiceB : "WrongB",
        choiceC : "WrongC",
        choiceD: "Hello",
        correct : "Hello"
    },{
        question : "What does CSS stand for?",
        choiceA : "Wrong",
        choiceB : "Correct",
        choiceC : "Wrong",
        correct : "B"
    },{
        question : "What does JS stand for?",
        choiceA : "Wrong",
        choiceB : "Wrong",
        choiceC : "Correct",
        correct : "C"
    }
];

mybtn1.addEventListener("click", pressbtn);
function pressbtn(){
  modal.style.display = "block";
  questionText.innerHTML = questions[0].question; 
  answerA.innerHTML = questions[0].choiceA;
  answerB.innerHTML = questions[0].choiceB;
  answerC.innerHTML = questions[0].choiceC;
  answerD.innerHTML = questions[0].choiceD;
}

HTML

<ul class="path-one-row">
    <li class="grid blue" id="myBtn1"></li>
    <li class="grid blue" id="myBtn2"></li>
    <li class="grid blue" id="myBtn3"></li>
    <li class="grid blue" id="myBtn4"></li>
</ul>

解决方案

方法1:利用ID规律循环绑定

你的按钮ID是按myBtn1、myBtn2的规律命名的,可以直接通过循环生成ID字符串,获取对应按钮并绑定事件,同时匹配questions数组的0起始索引:

let questions = [
    {
        question : "What is an Epidemics?",
        choiceA : "CorrectA",
        choiceB : "WrongB",
        choiceC : "WrongC",
        choiceD: "Hello",
        correct : "Hello"
    },{
        question : "What does CSS stand for?",
        choiceA : "Wrong",
        choiceB : "Correct",
        choiceC : "Wrong",
        correct : "B"
    },{
        question : "What does JS stand for?",
        choiceA : "Wrong",
        choiceB : "Wrong",
        choiceC : "Correct",
        correct : "C"
    }
];

// 循环处理4个按钮,与HTML中的按钮数量对应
for (let i = 1; i <= 4; i++) {
    const btn = document.getElementById(`myBtn${i}`);
    if (!btn) continue; // 按钮不存在则跳过
    
    btn.addEventListener("click", () => {
        const questionIndex = i - 1;
        // 检查是否有对应题目,避免数组越界报错
        if (questionIndex >= questions.length) {
            modal.style.display = "block";
            questionText.innerHTML = "暂无题目";
            answerA.innerHTML = "";
            answerB.innerHTML = "";
            answerC.innerHTML = "";
            answerD.innerHTML = "";
            return;
        }
        
        const targetQuestion = questions[questionIndex];
        modal.style.display = "block";
        questionText.innerHTML = targetQuestion.question; 
        answerA.innerHTML = targetQuestion.choiceA || "";
        answerB.innerHTML = targetQuestion.choiceB || "";
        answerC.innerHTML = targetQuestion.choiceC || "";
        answerD.innerHTML = targetQuestion.choiceD || "";
    });
}

方法2:通过父元素批量获取按钮(更灵活)

不需要依赖按钮ID,直接通过父元素path-one-row获取所有子按钮,这种方法无需关心ID命名,后期修改按钮ID或新增按钮都不用调整JS:

let questions = [
    {
        question : "What is an Epidemics?",
        choiceA : "CorrectA",
        choiceB : "WrongB",
        choiceC : "WrongC",
        choiceD: "Hello",
        correct : "Hello"
    },{
        question : "What does CSS stand for?",
        choiceA : "Wrong",
        choiceB : "Correct",
        choiceC : "Wrong",
        correct : "B"
    },{
        question : "What does JS stand for?",
        choiceA : "Wrong",
        choiceB : "Wrong",
        choiceC : "Correct",
        correct : "C"
    }
];

// 获取父元素下所有目标按钮
const buttons = document.querySelectorAll(".path-one-row .grid.blue");
buttons.forEach((btn, index) => {
    btn.addEventListener("click", () => {
        // 处理按钮数量超过题目数量的情况
        if (index >= questions.length) {
            modal.style.display = "block";
            questionText.innerHTML = "暂无题目";
            answerA.innerHTML = "";
            answerB.innerHTML = "";
            answerC.innerHTML = "";
            answerD.innerHTML = "";
            return;
        }
        
        const targetQuestion = questions[index];
        modal.style.display = "block";
        questionText.innerHTML = targetQuestion.question; 
        answerA.innerHTML = targetQuestion.choiceA || "";
        answerB.innerHTML = targetQuestion.choiceB || "";
        answerC.innerHTML = targetQuestion.choiceC || "";
        answerD.innerHTML = targetQuestion.choiceD || "";
    });
});

关键细节

  • 增加了数组越界判断:当按钮数量超过题目数量时,显示「暂无题目」,避免控制台报错
  • 用|| ""处理部分题目缺少choiceD的情况,防止页面显示undefined

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 23:50:25