开发者

How to tell if dynamically loaded image exists

I'm dynamically loading images from a different website into an asp.net ListView control like this:

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

Sometimes, the images don't exist and I need to change the src to a static path: src="/whatever/default.png". What is the fastest way I check if the image exists and update the src if it doesn't (any client side possibilities via jQ开发者_运维百科uery)? The ListView is paged and could contain a result set of thousands of records, so I'd only like to check the images that are on the current page to optimize performance. Thanks!


using jquery you can do it this way:

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

$('#imgId').load(function(){
 // ... loaded  
}).error(function(){
 // ... not loaded
 $(this).attr('src','/whatever/default.png');
});


I would just try loading the images, and if you get an error, fall back to a default:

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

EDIT: This solution might not work, so I'll supply you with an alternate one. When an image doesn't load, it theoretically has a width of 0 (assuming you didn't style the <img> tags). This code might work:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜