gpt4 book ai didi

javascript - 当迭代嵌套在嵌套在另一个数组中的对象中的数组时,jQuery click 方法返回未定义

转载 作者:行者123 更新时间:2023-11-30 00:19:52 24 4
gpt4 key购买 nike

为什么for in循环遍历第一个answer对象数组后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();
});
});

This question's fiddle

最佳答案

由于对象的 .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);
});

https://jsfiddle.net/zu9e5poh/10/

关于javascript - 当迭代嵌套在嵌套在另一个数组中的对象中的数组时,jQuery click 方法返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33557185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com