for循环中的jQuery.load()

jQuery .load() within a for loop

本文关键字:load jQuery 循环 for      更新时间:2023-09-26

我向服务器发送了一个ajax请求。然后我收到一个物体。对象看起来像这样:

{
    "payload": {
        "result": [
            "http://example.com/img1.jpg",
            "http://example.com/img2.jpg",
            "http://example.com/img3.jpg",
            "http://example.com/img4.jpg",
            "http://example.com/img5.jpg"
        ]
    }
}

然后我使用for循环遍历对象

if (typeof response.payload.result == 'object') {
    var ln = response.payload.result.length;
    var i;
    if (ln > 0) {
        for (i = 0; i < ln; i++) {
              /* this shows i was increased for every iteration */
              console.log(i);
          var current_img = response.payload.result[i];
          var img = $("<img />").attr('src', current_img)
           .load(function () {
                  console.log(i);
                  /* this logs the last iteration 4 times */
                $("#product-images").append(img);
          });
        }
    }
}

我的问题是只创建了(1)个图像元素。执行此代码后附加到DOM的单个元素是数组中最后一个元素的值。为什么jQuery.load()只在最后一次迭代中被调用?

if (typeof response.payload.result == 'object') {
    var ln = response.payload.result.length;
    var i;
    if (ln > 0) {
        for (i = 0; i < ln; i++) {
            (function (n) {
                var current_img = response.payload.result[i];
                var img = $("<img />").attr('src', current_img)
                    .load(function () {
                    console.log(n);
                    $("#product-images").append(img);
                });
            })(i);
        }
    }
}

我想你错过了这一行的分号

var img = $("<img />").attr('src', current_img)

并且您尚未指定要在其中加载图像的元素的选择器。