开发者

How to determine there is no image on the specified path

开发者 https://www.devze.com 2023-03-13 00:55 出处:网络
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..

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!"); 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号