在标签上重申's id,使用下面的for循环和jquery

reiterate over the label's id using the following for loop and jquery

本文关键字:for jquery 循环 id 标签      更新时间:2023-09-26

我有四个输入单选按钮,带有四个标签,每个标签都有自己的id(choice1、choice2、choice3、choice4)

我想使用下面的for循环和jquery来重申标签的id。然而,选择:["猿","猫","木","火柴"]没有出现。有人能帮我理解为什么它不起作用吗?

var allQuestions = [
    {
        question: "Take me out and scratch my head, I am now black but once was red.  What am I? ",
        choices: ["Ape", "Cat", "Wood", "Match"],
        correctAnswer: "Match"
    },
    {
        question: "My thunder comes before the lightning; My lightning comes before the clouds; My rain dries all the land it touches. What am I? ",
        choices: ["Sun-ray", "Ashes", "Volcano", "Lightning"],
        correctAnswer: "Volcano"
    },
    {
        question: "I'm the part of the bird that's not in the sky. I can swim in the ocean and yet remain dry. What am I? ",
        choices: ["Air", "Sponge", "Shadow", "Fire"],
        correctAnswer: "Shadow"
    }
];
for ( var i=0; i < allQuestions[0].choices.length; i++){
   $('#choice[i]').text(allQuestions[0].choices[i]);
}

试试这个,

$('#choice['+i+']').text(allQuestions[0].choices[i]);

而不是

$('#choice[i]').text(allQuestions[0].choices[i]);

试试这个:

for ( var i=0; i < allQuestions[0].choices.length; i++){
   $('#choice' + Number(i+1)).text(allQuestions[0].choices[i]);
   // i start from 0 so you need to plus 1 for it, #choice1, #choice2,...
}

试试这个

您的输入单选按钮id从1开始,因此此解决方案运行良好

$('#choice'+(i+1)).text(allQuestions[0].choices[i]);