最近工作的时候框架用的TP5+jquery;页面的整个数据都是从后端一次传过来的,不能直接在img标签上面去添加onerror事件;也试过获取页面需要检测的所有图片,循环判断添加onerror事件,发现添加成功后页面刷新会进入死循环,这里给大家推荐一种方法
$(document).ready(function(){
$('.mainContent img').each(function(){ //获取需要判断的所有图片并且循环判断
var error = false;
if (!this.complete) {
error = true;
}
if (typeof this.naturalWidth != "undefined" && this.naturalWidth == 0) {
error = true;
}
if(error){
$(this).bind('error.replaceSrc',function(){
this.src = "默认图片.png";
$(this).unbind('error.replaceSrc');
}).trigger('load');
}
});
});