【问题标题】:Why changing src of an image is async?为什么更改图像的 src 是异步的?
【发布时间】:2012-03-12 03:34:32
【问题描述】:

我有这样的事情:

<div id="container">
 <img id="screenFirstImg">
</div>

还有js:

$('a.screenThumbLink').click(function(){

  console.log( $('#container').height() );
    $('img.screenFirstImg').attr('src','new src');
  console.log( $('#container').height() );

});

基本上只需单击缩略图,screenFirstImage 就会更改(带有更大的图像)。但是console.log显示了完全相同的高度数字,这是不可能的,因为在我设置了新的src之后,容器变得更大了。

也许那是因为当我执行第二个 console.log 时,图像尚未加载。
加载img后如何获取.height?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:
    $("#container img").load(function () {
      console.log( $("#container").height() );
    });
    
    $('a.screenThumbLink').click(function(){
      $('img.screenFirstImg').attr('src','new src');
    });
    

    【讨论】:

    • @yes123 是的。这是.load() 的文档。你可能把它和.load() 混淆了;-)
    【解决方案2】:

    将您的代码更改为

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

    【讨论】:

      【解决方案3】:

      将 onload 事件附加到图像,当图像加载完毕后触发该事件,然后您可以做任何您需要的事情。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-30
        • 2013-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多