2014-09-10 123 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作为第二个参数并改为使用该参数。