2010-11-05 59 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; 
      }); 
} 
相關問題