Having quoted the results with $ .each, how do you feel about the index of the current iteration?

If I dwell on the results of a JSON call, how do I know if I am in the first iteration?

In this example, I compiled a variable loopIndexto indicate what I am looking for, but it is not actually set anywhere.

How do you know where you are in the loop - what iteration are you on?

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

  });
});
+3
source share
4 answers

The first callback parameter $.each()is an index, for example:

$.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!");
     }
  });
});

Signature for .Query.each():

jQuery.each(collection, callback(indexInArray, valueOfElement))
+7
source
  $.each(data.results, function(loopIndex) {
     .....

as shown in the documentationjQuery.each .

+1
source

:

$.each(data.results, function(index) {
    // what 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;
          });
}
0

Source: https://habr.com/ru/post/1773228/


All Articles