2012-10-30 95 views
-1

这里是一个函数的片段。我得到每个图像的原始大小。然后我想做一个简单的if语句,但不能访问变量'imageWidth'。在'theImage.onload = function()'之外获得'undefined'。它是如何超出范围的?从加载函数访问变量

var parentWidth = $('figure.pack_image').width(); 
    var screenImage = $('figure.pack_image img'); 
    var imageWidth = ''; 

    screenImage.each(function() { 

     var theImage = new Image(); 
     theImage.src = $(this).attr('src'); 

     theImage.onload = function() { 
      imageWidth = this.width; 

     } 

     if (imageWidth > parentWidth) { 
     ... 
+1

异步回调..再次... – gdoron

回答

1

它不是“超出范围”,它只是没有价值。您不能测试imageWidth,直到它被设置,并且.onload调用是异步的。

您的测试需要.onload函数内要启动:

theImage.onload = function() { 
    imageWidth = this.width; 
    if (imageWidth > parentWidth) { 
     ... 
    } 
} 

,或者使用延迟回调解除嵌套从后续处理onload逻辑:

var gotImage = $.Deferred(); 
theImage.onload = function() { 
    gotImage.resolve(this); 
} 

gotImage.done(function(img)) { 
    if (img.width > parentWidth) { 
     ... 
    } 
}); 
+0

嘿谢谢。我以前已经完成了你的第一个解决方案,但是这又产生了另一个问题现在所有完成, – user924248

+0

@ user924248我要稍微重写第二个版本来传递图像对象本身,而不是它的宽度。这将使该方法在将来更加灵活。 – Alnitak