jQuery: Check if image exists

穿精又带淫゛_ 提交于 2019-11-26 07:35:46

问题


I\'m loading an image path via jQuery $.ajax and before showing the image I\'d like to check if it in fact exists. Can I use the image load/ready event or something similar to determine that the file path is valid?

Having .myimage set to display: none, I\'m hoping to do something like

$(\".myimage\").attr(\"src\", imagePath);
$(\".myimage\").load(function() {
    $(this).show();
});

Is anything like that possible?


回答1:


Well, you can bind .error() handler...

like this,

$(".myimage").error(function(){
  $(this).hide();
});

well, yours is okay already with load-event

$(".myimage").load(function() {
    $(this).show();
});

the problem with this is if Javascript was disabled the image will not ever show...




回答2:


Try:

function urlExists(testUrl) {
 var http = jQuery.ajax({
    type:"HEAD",
    url: testUrl,
    async: false
  })
  return http.status;
      // this will return 200 on success, and 0 or negative value on error
}

then use

if(urlExists('urlToImgOrAnything') == 200) {
    // success
}
else {
    // error
}



回答3:


An old thread I know but I think it could be improved. I noticed OP having intermittent problems which could be due to loading of the image and error checking simultaneously. It would be better to let the image load first and then check for errors:

$(".myimage").attr("src", imagePath).error(function() {
    // do something
});



回答4:


Since you're already doing an AJAX request, I would offload this to the server-side app that is supporting your AJAX. It's trivial to check to see if a file exists from the server, and you could set variables in the data you send back to specify results.




回答5:


This question is a couple years old, but here's a better example usage for the error handler for anyone looking at this.

$("img")
  .error(function(){
    $(this).hide();
  })
  .attr("src", "image.png");

You need to attach the error handler before you try to load the image in order to catch the event.

Source: http://api.jquery.com/error/




回答6:


This is what I did of mine:

$.get( 'url/image', function(res){ 
    //Sometimes has a redirect to not found url
    //Or just detect first the content result and get the a keyword for 'indexof'
    if ( res.indexOf( 'DOCTYPE' ) !== -1 )  {
        //not exists
    } else {
        //exists
    }
});


来源:https://stackoverflow.com/questions/3327655/jquery-check-if-image-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!