JQuery check image exist

2019-09-24 05:47发布

问题:

Hi i'm trying to display different image in different part of my site, but i need to display a default image if image doesn't exist.

here is my code: the problem is to check the img width but is alway

jQuery(document).ready(function () {

    var $pathname = window.location.pathname;
    $item = 'http://www.lotus-nascita.it/images/headers-hover/corsi-preparto.jpg';
    if ($pathname == '/') {
        $pathname = $pathname + 'home';
        $item = 'http://www.lotus-nascita.it/images/headers-hover' + $pathname + '.jpg';

    }
    var img = new Image();
    img.onload = function () {}
    img.src = $item;
    if (img.height != 0) {

        $item = 'http://www.lotus-nascita.it/images/headers-hover' + $pathname + '.jpg';
    }

    jQuery('#header').fadeOut('fast', function () {
        jQuery('#header').css({
            "background": 'url("' + $item + '")'
        });
        jQuery('#header').fadeIn('slow');

    });
});

回答1:

The height is always zero, as you have to wait for the image to load before it has a height ?

var item = 'http://www.lotus-nascita.it/images/headers-hover' + $pathname + '.jpg';
var img  = new Image();

img.onload = function () {
  if (this.height === 0) {
      item = 'http://www.lotus-nascita.it/images/headers-hover/corsi-preparto.jpg';
  }
}
img.src = item;


回答2:

I would try something like this in vanilla:

<img src="image.gif" onerror="this.src = 'default.gif'">

Or jQuery:

$(img).error(function() {
   $(this).attr("src","default.gif");
}).attr("src",$item);


回答3:

Try

var $myImg = $("<img>").attr("src", $item);
if($myImg.height != 0) { ... }