为什么在for for循环迭代第一个答案对象数组后,click方法返回undefined?
var i = 0;
var j = 0;
var allQuestions = [{question:"What is the color of the sky?",answer:["blue","yellow",
"red"],correctAnswer:["blue",1]},{question:"What is the opposite of
up?",answer:["down","sideways", "circle"],correctAnswer:["down",1]},
{question:"What is the first number?",answer:["1","5", "7"],correctAnswer:
["1",1]}];
$(document).ready(function() {
function changeQuestion() {
$("#radios").empty();
for( answers in allQuestions[i].answer) {
var radioBtn = $('<input type="radio" class="radios" name="btnAnswers" value="'+
allQuestions[i].answer[j] + '" /><label for ="secondbtn">'
+ allQuestions[i].answer[j] + '</label>');
radioBtn.appendTo('#radios');
alert(allQuestions[i].answer[j]);
j++;
}
i++;
return true;
};
$("#nextbtn").click(function(){
changeQuestion();
});
});
答案 0 :(得分:1)
由于对象的.answer
属性是一个数组,您可以使用
for(var j=0; allQuestions[i].answer.length; j++) {...}
而不是
for(answers in allQuestions[i].answer) {...}
完整代码将是:
$(document).ready(function() {
var i = 0;
function changeQuestion() {
$("#radios").empty();
var obj = allQuestions[i];
for(var j=0; j<obj.answer.length; j++) {
$('<input type="radio" class="radios" name="btnAnswers" value="' + obj.answer[j] + '" /><label for ="secondbtn">' + obj.answer[j] + '</label>').appendTo('#radios');
}
i++;
};
$("#nextbtn").click(changeQuestion);
});
答案 1 :(得分:0)
你必须将值初始化为变量i&amp; Ĵ
将代码修改为
$(document).ready(function() {
function changeQuestion() {
$("#radios").empty();
var i=0, j=0;
for( answers in allQuestions[i].answer) {
var radioBtn = $('<input type="radio" class="radios" name="btnAnswers" value="'+
allQuestions[i].answer[j] + '" /><label for ="secondbtn">'
+ allQuestions[i].answer[j] + '</label>');
radioBtn.appendTo('#radios');
alert(allQuestions[i].answer[j]);
j++;
}
i++;
return true;
};
$("#nextbtn").click(function(){
changeQuestion();
});
});