使用以下for循环和jquery重复标签的id

时间:2013-12-12 04:47:40

标签: javascript jquery

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

我想使用以下for循环和jquery重复标签的id。但是,选项:[“Ape”,“Cat”,“Wood”,“Match”]没有出现。有人能帮我理解为什么它不起作用吗?

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]);
}

3 个答案:

答案 0 :(得分:1)

试试这个,

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

而不是

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

答案 1 :(得分:0)

试试这个

您的输入单选按钮ID从1开始,因此此解决方案正常

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

答案 2 :(得分:0)

试试这个:

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,...
}