How to detect broken image and replace with another?

前端 未结 3 794
不思量自难忘°
不思量自难忘° 2021-02-10 17:46

I have a page which displays lots of images from different remote servers. http://example.com/img/email_star0.png\' height=\'150\' />

Now suppose this image is not prese

相关标签:
3条回答
  • 2021-02-10 18:21

    I don't think it is possible to check if image exists on remote server without using curl or jQuery. But jQuery snippet bellow reacts on image loading error by replacing it with a local one, maybe that's what you are looking for.

    $(document).ready(function(){
      $('img').error(function(){
         $(this).attr('src', 'http://mysite/myimage.jpg');
      });
    });
    
    0 讨论(0)
  • 2021-02-10 18:24

    You can use the 'onerror' attribute directly in the image tag:

    <img src="my_images.jpg" onerror="this.src='my_replacement.jpg'">
    
    0 讨论(0)
  • 2021-02-10 18:30

    Yes this is possible using onerror event:

    <img src="your_image_source" onerror="this.src='/path/to/local/file'">
    

    If the image does not exist, instead of displaying the X, this will show the default image in your local folder

    0 讨论(0)
提交回复
热议问题