2015-11-06 59 views
2

爲什麼在for循環迭代第一個應答對象數組後,click方法返回undefined?jQuery 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

+1

'i'和'j'初始化在哪裏? –

+0

@ Roamer-1888對不起,沒有在最初的帖子中添加它們。他們現在在那裏,但仍然無法工作。 – Stu

回答

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

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

+0

感謝這工作!你能解釋一下(或者提供鏈接)爲什麼第二輪changeQuestion中的「for in」循環返回undefined? – Stu

+0

你的'for(... in)'結構實際上並不是罪魁禍首。這是'j'計數器,它繼續遞增,所以在第二次運行時,它將從3開始。如果要在'changeQuestion()'內部移動'var j = 0',那麼它將被重置爲零每次運行的開始。在我的版本中,for(var j = 0; ...)具有完全相同的效果。 –

+0

感謝您的支持! – Stu

0

你必須初始化值變量我&Ĵ

修改代碼以

$(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(); 
}); 

});

+0

@MJD我在小提琴中添加了初始化和數組,以及一個警告,以顯示代碼如何步驟,但它仍然不工作。 – Stu