2015-09-20 157 views
1

我试图使用jQuery推迟对象推左div #image_viewer只有所有的图像已经通过Ajax调用预加入它后。jQuery延迟不工作

function myFunc() { 
      return $.Deferred(function(apples) { 
      for (j=0; j< otherimages_details.length; j++) { 
      var otherimage = "<img class='otherimage' title='" + otherimages_details[j][0] + "'" + "src='" + 'user/' + username_cookie + "_albums/" + otherimages_details[j][1] + "'>"; 
      var images = images + image; } 
      $('#imageviewer_otherimages').prepend(images); 
      apples.resolve(); 
      }).promise(); 
      } 


      $.when(myFunc()).then(function() { 
          var left = (($(window).width() - $('#image_viewer').width() - $('#imageviewer_otherimages').width())/2);  
          $('#image_viewer').css("left", left)}); 

这不起作用。在所有图像加载到它之前,仍然会推送#image_viewer。使用load事件img元素的

回答

0

所有图像可能不被加载时apples.resolve();$('#imageviewer_otherimages').prepend(images);

尝试创建for循环中推迟每个图像调用,解决load处理器,$.when.apply内推迟到解决​​当所有的图像加载

注意,关于var images = images + image;的预期结果不确定吗?

function myFunc() { 
    var arr = otherimages_details.map(function(img, j) { 
       var dfd = $.Deferred(); 
       var image = $("<img class='otherimage' title='" 
          + img[0] 
          + "'>"); 
       image.on("load", function() { 
       dfd.resolve(this) 
       }) 
       .attr("src", "user/" + username_cookie 
          + "_albums/" 
          + img[1]) 
       // ? 
       // var images = images + image; 
       return d.promise() 
      }); 
      return $.when.apply($, arr)   
      .then(function() { 
       $('#imageviewer_otherimages') 
       .prepend(arguments); 
      }) 
} 


myFunc() 
.then(function() { 
var left = (($(window).width() - $('#image_viewer').width() 
      - $('#imageviewer_otherimages').width())/2);  
$('#image_viewer').css("left", left) 
}); 
+0

感谢您的快速回复!我稍后再检查一下,不得不冲出去。顺便说一句,我在我的原始代码中犯了一个错误。 'var otherimage'应该是'var image'。这解释了'var images = images + image'代码。发生的事情是数据库中有多少个图像。 'for(j = 0 ...)'循环遍历这些图像,每一轮都将它们放入'var images'中。在循环结束时,'var images'将会在数据库中找到所有图像。 – blurgoon

+0

@blurgoon另请参见http://stackoverflow.com/questions/29044852/preloading-images-in-html – guest271314