迭代jquery对象
问题描述:
我试图迭代并输出选项属性的值使用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));
});
答
试试这个
$(info[0].choices).each(function(value){
$('#answers').append($('<li>').text(this));
答
你是路过的,而不是价值指数:
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/
答
的$.each
回调需要两个参数index
和value
。添加value
作为第二个参数并改为使用该参数。
答
你都弄得
$(selector).each()
与
$.each(array, callback)
http://api.jquery.com/jquery.each/
你想使用第二种形式用于遍历数组。
回调的第一个参数是'index',你应该使用第二个参数。 – undefined 2014-09-10 17:44:41
给每个()回调的参数都搞乱了。你想为价值的第二个参数,不要问我为什么arity是这样的。 – dandavis 2014-09-10 17:44:45
如果您使用的是不熟悉的方法,我建议[先阅读**文档**](http://api.jquery.com/each/)。 *“为什么是这样?”*因为这就是该方法的工作原理。 – 2014-09-10 17:49:38