检测地图何时结束并且imgs加载了jquery

时间:2015-03-06 08:29:27

标签: jquery

 var xhr = $.ajax({
    type: 'GET',
    url: url,
    async: false,
    jsonpCallback: 'jsonCallback',
    contentType: "application/json",
    dataType: 'jsonp',
    success: function(json, responseText, req) {
    if (typeof json.data != "undefined") {
        json.data.map(function(product) {
          markAvailable(product, lookRequestId);
        });
      } else {
        //console.log("successfull request but no products in array");
      } 
});



function markAvailable(product, lookRequestId) {
   $(".qv-overlay-container-" + lookRequestId + " [data-product-pid-thumb=" + product.id + "]").append('<img src='+product.image_groups[0].images[0].link+' />');
}

我使用data.map遍历产品列表,并为每个产品调用函数markAvailable。有没有办法在这个进程结束时,当data.map的循环结束时,我可以执行一些代码?理想情况下,我希望在附加后加载所有图像时执行代码。

2 个答案:

答案 0 :(得分:0)

如果您还要等待加载图片,请尝试

var xhr = $.ajax({
    type: 'GET',
    url: url,
    async: false,
    jsonpCallback: 'jsonCallback',
    contentType: "application/json",
    dataType: 'jsonp',
    success: function (json, responseText, req) {
        if (typeof json.data != "undefined") {
            var promises = json.data.map(function (product) {
                return markAvailable(product, lookRequestId);
            });
            $.when.apply($, promises).then(function () {
                //do your stuff here
            })
        } else {
            //console.log("successfull request but no products in array");
        }
    })
});

function markAvailable(product, lookRequestId) {
    var deferred = $.Deferred();
    var $img = $('<img src=' + product.image_groups[0].images[0].link + ' />').appendTo(".qv-overlay-container-" + lookRequestId + " [data-product-pid-thumb=" + product.id + "]");
    $img.on('load error', function () {
        deferred.resolve();
    })
    return deferred.promise();
}

答案 1 :(得分:0)

您可以使用以下方式查看最后一项:

json.data.map(function(product, idx) {
    if ( idx == json.data.length ){
       //your job here
    }
    markAvailable(product, lookRequestId);
});