正在迭代jquery对象

Iterating jquery objects

本文关键字:对象 jquery 迭代      更新时间:2023-09-26

我正试图使用jqueryeach()迭代并输出choices属性的值。我的代码似乎输出的是数组索引,而不是字符串值。为什么会这样?这是我的jsfiddle

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

您混淆了

$(selector).each()

http://api.jquery.com/each/

带有

$.each(array, callback)

http://api.jquery.com/jquery.each/

您希望使用第二种形式对数组进行迭代。

您传递的是索引而不是值:

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/

试试这个

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

$.each回调接受两个参数indexvalue。添加value作为第二个参数,然后使用该参数。