1

我正在将来自不同网站的图像动态加载到 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 是分页的,可能包含数千条记录的结果集,所以我只想检查当前页面上的图像以优化性能。谢谢!

4

2 回答 2

2

使用 jquery 你可以这样做:

<img src="http://myimages.com/image.jpg" id="imgId" />

$('#imgId').load(function(){
 // ... loaded  
}).error(function(){
 // ... not loaded
 $(this).attr('src','/whatever/default.png');
});
于 2011-03-31T16:05:11.677 回答
0

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

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

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

$('img').each(function()
{
  if ($(this).width() == '0px')
  {
    $(this).attr('src', '/whatever/default.png');
  }
});
于 2011-03-31T16:04:46.837 回答