简体   繁体   English

迭代jQuery对象

[英]Iterating jquery objects

I am attempting to iterate and output the values of the choices property using jquery each( ). 我试图使用jquery each( )迭代并输出choices属性的值。 My code seems to output the array index and not the string values. 我的代码似乎输出数组索引而不是字符串值。 why is this? 为什么是这样? Here is my jsfiddle 这是我的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));
});

You have confused 你很困惑

$(selector).each()

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

with

$.each(array, callback)

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

You want to use the second form for iterating over arrays. 您想使用第二种形式遍历数组。

You are passing the index instead of the value: 您正在传递索引而不是值:

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

Here's an example fiddle: http://jsfiddle.net/436Lcvc4/ 这是一个小提琴示例: http : //jsfiddle.net/436Lcvc4/

try this one 试试这个

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

The $.each callback takes two arguments index and value . $.each回调采用两个参数indexvalue Add value as the second argument and use that argument instead. value添加为第二个参数,并改用该参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM