【问题标题】:How to tell if dynamically loaded image exists如何判断动态加载的图像是否存在
【发布时间】:2011-07-27 01:03:01
【问题描述】:

我正在将来自不同网站的图像动态加载到 asp.net ListView 控件中,如下所示:

<ListView>
   <ItemTemplate>
      <img src='<%# string.Format("http://www.Website.com/Images/{0}", Eval("ImageName")) %>' />

有时,图像不存在,我需要将 src 更改为静态路径:src="/whatever/default.png"。我检查图像是否存在并更新 src(如果不存在)的最快方法是什么(通过 jQuery 的任何客户端可能性)? ListView 是分页的,可能包含数千条记录的结果集,所以我只想检查当前页面上的图像以优化性能。谢谢!

【问题讨论】:

    标签: jquery asp.net ajax file-exists


    【解决方案1】:

    使用 jquery 你可以这样做:

    <img src="http://myimages.com/image.jpg" id="imgId" />
    
    $('#imgId').load(function(){
     // ... loaded  
    }).error(function(){
     // ... not loaded
     $(this).attr('src','/whatever/default.png');
    });
    

    【讨论】:

    • 谢谢。最终解决方案,它处理更新面板内的部分回发: $(document).ready(function () { LoadCheck(); var prmInstance = Sys.WebForms.PageRequestManager.getInstance(); prmInstance.add_endRequest(function () { LoadCheck( ); }); }); function LoadCheck() { $('.ThumbnailImage').load(function () { }).error(function () { $(this).attr('src', 'website.com/images/default.jpg'); }); }
    【解决方案2】:

    我会尝试加载图像,如果出现错误,请回退到默认值:

    $('img').error(function()
    {
      $(this).attr('src', '/whatever/default.png');
    });
    

    编辑:此解决方案可能不起作用,因此我将为您提供替代解决方案。当图像加载时,理论上它有一个width0(假设您没有设置&lt;img&gt; 标签的样式)。此代码可能有效:

    $('img').each(function()
    {
      if ($(this).width() == '0px')
      {
        $(this).attr('src', '/whatever/default.png');
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2010-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多