2010-11-05 58 views
3

如果我通过JSON调用的结果循环,我怎么知道我是否在第一次迭代?

在这个例子中,我编制了loopIndex变量来表示我在找什么 - 但它并没有真正设置在任何地方。

您如何知道自己在循环中的位置 - 您正在进行哪种迭代?

$.getJSON(myurl, function(data) { 
    $.each(data.results, function() { 
    // what's the index of this iteration? 
    if(loopIndex==0){ 
     console.log("first iteration!"); 
    } 

    }); 
}); 
+0

阅读文档没有奇迹。 :) – epascarello 2010-11-05 12:33:12

回答

7

$.each()回调的第一个参数是索引,就像这样:

$.getJSON("http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsSearch?term=paparazzi+lady+gaga&callback=?", function(data) { 
    $.each(data.results, function(i, item) { 
    if(i==o) { 
     console.log("first iteration!"); 
    } 
    }); 
}); 

.Query.each()的签名是:

jQuery.each(collection, callback(indexInArray, valueOfElement)) 
0

尝试以下操作:

$.each(data.results, function(index) { 
    // what's the index of this iteration? 
    alert(index); 
}); 
0

这里是另一个例子

function emailform(rtndata) { 
     $.each(rtndata.products, function (i, product) { 
      $("<img/>").attr({ 
        src: product.imageLargeUrl, 
        title: product.name, 
        width: 100, 
        height: 100 
      }).appendTo(".images"); 
      $('.question').html(rtndata.title); 
      if (i == 1) return false; 
      }); 
} 
相关问题