How to determine there is no image on the specified path
I want to know how can i determine whether an image is ava开发者_StackOverflow中文版ilable on the specified path or not. I want to display an error message if there is no image on the specified path...
For eg:
<img src="images/products/default.bmp" alt="NoImage"/>
but if there is no image default.bmp on this path then alt Noimage will be displayed but apart from this i also want to display an error message...for this i need to determine that there is no image, how can i. Please Reply
Thanks Romi
Using jQuery
$('img').error(function(){
console.log('error');
});
Another way
var img = document.getElementsByTagName('img')[0];
if(img.complete){
console.log('loaded');
}else{
console.log('not loaded');
}
Use the img "onerror" event, e.g.
<img id="image" alt='img' src="myImg.gif"/>
<script>
function noImg() {
alert("Can't find image!");
}
document.getElementById("image").onerror = noImg;
</script>
It gets fired if the img src can't be found or loaded.
You can also check the width of the image, if it is 0:
if ( $(‘#imageID’).getwidth() == 0 ) {
alert("Can't find image!");
}
精彩评论