开发者

Way to detect broken images in javascript? [duplicate]

开发者 https://www.devze.com 2023-01-12 06:38 出处:网络
This question already has answers here: jQuery/JavaScript to replace broken images (32 answers) 开发者_JAVA百科
This question already has answers here: jQuery/JavaScript to replace broken images (32 answers) 开发者_JAVA百科 Closed 6 years ago.

I need to be able to detect if an image is broken and replace with a default image if the image link is broken. I know i could do this with an image proxy, but was hoping to do it on the fly with javascript.


I believe it's the onerror event of the img element. onerror=function(){} though i've never used it.


As any event the onerror will propagate upwards on the DOM, so you could make a generic handler for this type of errors.

<script type="text/javascript">
jQuery(document).bind('error', function(event) {
  console.log(event.target.src);
});
</script>


You can use <img onerror='doWhateverFunction()' etc etc

http://msdn.microsoft.com/en-us/library/cc197053(v=VS.85).aspx


Example of code:

<script language='javascript'>
function defaultImage(img)
{
    img.onerror = "";
    img.src = 'default.gif';
}
</script>
<img alt="My Image" src="someimage.gif" onerror="defaultImage(this);" />
0

精彩评论

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