【问题标题】:While looping through results with $.each, how do you refer to the index of the current iteration?在使用 $.each 循环遍历结果时,如何引用当前迭代的索引?
【发布时间】:2010-11-05 12:18:57
【问题描述】:

如果我正在循环访问 JSON 调用的结果,我如何知道我是否处于第一次迭代中?

在此示例中,我创建了 loopIndex 变量来指示我要查找的内容 - 但它实际上并未设置在任何地方。

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

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

  });
});

【问题讨论】:

  • 阅读文档可以创造奇迹。 :)

标签: jquery loops iterator


【解决方案1】:

$.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))

【讨论】:

    【解决方案2】:
      $.each(data.results, function(loopIndex) {
         .....
    

    documentation of jQuery.each所示。

    【讨论】:

      【解决方案3】:

      尝试以下:

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

      【讨论】:

        【解决方案4】:

        这是另一个例子

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

        【讨论】:

          猜你喜欢
          • 2011-03-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-12
          • 1970-01-01
          相关资源
          最近更新 更多