为什么更改图像的src是异步的?

我有这样的事情:

并且js:

 $('a.screenThumbLink').click(function(){ console.log( $('#container').height() ); $('img.screenFirstImg').attr('src','new src'); console.log( $('#container').height() ); }); 

基本上单击screenFirstImage会更改screenFirstImage (使用更大的图像)。 但是console.log显示了完全相同的高度数,并且这是不可能的,因为在我设置新的src之后容器变大了。

也许这就是因为当我做第二个console.log时,图像还没有加载。
加载img后如何获得.height?

 $("#container img").load(function () { console.log( $("#container").height() ); }); $('a.screenThumbLink').click(function(){ $('img.screenFirstImg').attr('src','new src'); }); 

将您的代码更改为

 $('a.screenThumbLink').click(function(){ console.log( $('#container').height() ); $('img.screenFirstImg') .one('load', function(){ console.log( $('#container').height() ); }) .attr('src','new src'); }); 

将onload事件附加到图像,然后在图像加载时触发,然后您可以执行任何操作。