Как проверить, существует ли изображение с данным URL?

Я хочу проверить, существует ли изображение с помощью jQuery.

Например, как я проверяю, что это изображение существует

http://www.google.com/images/srpr/nav_logo14.png 

проверка должна дать мне 200 или состояние хорошо

--------------отредактированный-------------------

var imgsrc = $(this).attr('src');
var imgcheck = imgsrc.width;


if (imgcheck==0) {
alert("You have a zero size image");
} else { //do rest of code }

Спасибо Jean

76
задан Huangism 1 July 2015 в 11:59
поделиться

2 ответа

Используйте обработчик ошибки следующим образом:

$('#image_id').error(function() {
  alert('Image does not exist !!');
});

Если изображение не может быть загружено (например, потому что оно отсутствует по указанному URL-адресу), предупреждение будет отображается:

Обновление:

Я думаю, что использования:

$.ajax({url:'somefile.dat',type:'HEAD',error:do_something});

будет достаточно для проверки наличия 404.

Дополнительные материалы:

Обновление 2:

Ваш код должен быть таким:

$(this).error(function() {
  alert('Image does not exist !!');
});

Эти строки и который все равно не проверяет, существует ли удаленный файл:

var imgcheck = imgsrc.width;    

if (imgcheck==0) {
  alert("You have a zero size image");
} else { 
  //execute the rest of code here 
}
77
ответ дан 24 November 2019 в 11:18
поделиться

Из здесь :

// when the DOM is ready
$(function () {
  var img = new Image();
  // wrap our new image in jQuery, then:
  $(img)
    // once the image has loaded, execute this code
    .load(function () {
      // set the image hidden by default    
      $(this).hide();
      // with the holding div #loader, apply:
      $('#loader')
        // remove the loading class (so no background spinner), 
        .removeClass('loading')
        // then insert our image
        .append(this);
      // fade our image in to create a nice effect
      $(this).fadeIn();
    })
    // if there was an error loading the image, react accordingly
    .error(function () {
      // notify the user that the image could not be loaded
    })
    // *finally*, set the src attribute of the new image to our image
    .attr('src', 'images/headshot.jpg');
});
4
ответ дан 24 November 2019 в 11:18
поделиться
Другие вопросы по тегам:

Похожие вопросы: