在javascript中检测破碎图像的方法?

Rod*_*son 9 javascript jquery

我需要能够检测图像是否被破坏,并在图像链接断开时替换为默认图像.我知道我可以使用图像代理执行此操作,但希望能够使用javascript动态执行此操作.

med*_*iev 13

我相信这onerrorimg元素的事件.onerror=function(){}虽然我从来没用过它.


Rob*_*ert 5

您可以使用<img onerror='doWhateverFunction()'

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


mhi*_*tza 5

任何事件onerror都会在DOM上向上传播,因此您可以为此类错误创建一个通用处理程序.

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