2013-04-17 38 views
1

看来,由于某种原因.load方法不起作用。在这里我的jquery:动态加载的图像返回0的外部高度(jQuery)

$(document).ready(function() { 
    var imgHeight; 
    $('body').prepend('<img src="http://farm9.staticflickr.com/8266/8653931785_4a8d43164f.jpg" class="select" />'); 
    if($('img.select').prop('complete')) { 
     imgHeight = $('img.select').outerHeight(); 
    }else{ 
     $('img.select').load(function() { 
      imgHeight = $('img.select').outerHeight(); 
     });  
    } 
    $('body').prepend('<p>Image Height: ' + imgHeight + '</p>'); 
}); 

和一个jsfiddle

链接的例子运行之后几次(我假设图像缓存),它会成功找回正确的高度。这告诉我if($('img.select').prop('complete'))工作正常。

我在这里错过了什么?

(在Chrome和FF测试)

编辑: 好了,现在,如果我想,如果他们被加载,检查不止一个形象是什么? $('img.select').prop('complete')只测试匹配选择器的第一个元素。 http://jsfiddle.net/hcarleton/2Dx5t/6/

回答

2

编辑更新使用one(),而不是过时load()

load()是aysnchronous,所以之前不会设置imgHeight值您致电$('body').prepend('<p>Image Height: ' + imgHeight + '</p>'); 。此外,从jQuery 1.8起,不推荐使用load()事件处理函数。

最好是将一个委派的负载监听器附加到任何图像的主体上,使用.select类。在该事件处理程序的回调中,您可以检测图像高度。

$(document).ready(function() { 
    $('body').one('load', 'img.select', function(e) { 
     var imgHeight = $('img.select').outerHeight(); 
     $('body').prepend('<p>Image Height: ' + imgHeight + '</p>'); 
    });  

    $('body').prepend('<img src="http://farm9.staticflickr.com/8266/8653931785_4a8d43164f.jpg" class="select" />'); 
}); 
+0

谢谢,现在有道理。 –

+1

load()这里用来使用回调函数来绑定事件,而不是函数。你有异步函数.load(),但它有一个不同的sig。 –

+0

也发现load()事件处理程序自jquery 1.8开始已弃用。我会更新我的答案。 – cfs

1

用这个代替:

SEE DEMO

$(document).ready(function() { 
    var imgHeight; 
    $('body').prepend('<img src="http://farm9.staticflickr.com/8266/8653931785_4a8d43164f.jpg" class="select" />'); 
    $("img").one('load', function() { 
     imgHeight = $(this).outerHeight(); 
     $('body').prepend('<p>Image Height: ' + imgHeight + '</p>'); 
    }).each(function() { 
     if (this.complete) $(this).load(); 
    }); 

}); 
+0

你能解释一下你的答案吗?复制和粘贴不会帮助我。我需要解释为什么这会起作用。 –

+0

有时load()事件不会针对缓存/断开的图像(旧浏览器)触发,或者有时会由于浏览器行为而触发多次。这解释了一个和每个。你最初的问题是,这里的加载是一个事件(使用回调函数),只有当事件被触发时才被调用。所以,在你最初的代码中,imgHeight在你尝试使用它之前从未被定义过。 –