2014-09-10 124 views
-1

我試圖迭代並輸出選項屬性的值使用jquery each()。我的代碼似乎輸出數組索引,而不是字符串值。爲什麼是這樣?這是我jsfiddle迭代jquery對象

var allQuestions = [ 
    { 
    question: "Who is Prime Minister of the United Kingdom?", 
    choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"], 
    correctAnswer:0 
    }]; 


$(info[0].choices).each(function(value){ 
    $('#answers').append($('<li>').text(value)); 
}); 
+2

回調的第一個參數是'index',你應該使用第二個參數。 – undefined 2014-09-10 17:44:41

+0

給每個()回調的參數都搞亂了。你想爲價值的第二個參數,不要問我爲什麼arity是這樣的。 – dandavis 2014-09-10 17:44:45

+1

如果您使用的是不熟悉的方法,我建議[先閱讀**文檔**](http://api.jquery.com/each/)。 *「爲什麼是這樣?」*因爲這就是該方法的工作原理。 – 2014-09-10 17:49:38

回答

0

試試這個

$(info[0].choices).each(function(value){ 
    $('#answers').append($('<li>').text(this)); 
1

你是路過的,而不是價值指數:

var allQuestions = [{ 
    question: "Who is Prime Minister of the United Kingdom?", 
    choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"], 
    correctAnswer:0 
}]; 


$(info[0].choices).each(function(index, value){ 
    $('#answers').append($('<li>').text(value)); 
}); 

下面是一個例子小提琴:http://jsfiddle.net/436Lcvc4/

0

$.each回調需要兩個參數indexvalue。添加value作爲第二個參數並改爲使用該參數。