我正在使用 for 循环向用户显示一系列缩略图。如果 thumbnails[i].path
加载失败,我要加载 thumbnail_unavailable.jpg
在它的位置。
据我了解,jQuery 的 .error()
处理程序应按如下方式使用。
for (var i=0; i<thumbnails.length; i++){
var txt = "";
txt += "<div class...>";
// if no image, load "Screenshot Unavailable" thumbnail
var temp_img = $('<img id="'+thumbnails[i].video_id+'" />');
temp_img.error(function () {
// temp_img.attr doesn't work
temp_img.attr('src','images/thumbnail_unavailable.jpg');
// nor does: $('#'+thumbnails[i].video_id).attr('src','...jpg');
// nor does: $(this).attr('src','...jpg');
}).attr('src', thumbnails[i].path);
txt += temp_img.get(0).outerHTML;
txt += "</div>";
$('#putVidThumbsHere').append(txt);
}
但是,缩略图保留了其损坏的
thumbnail[i].path
不管我是否使用 $(this)
$('#'...
或 temp_img
最佳答案
我尝试了所有方法,包括 on
/one
绑定(bind)来处理失败的资源。不知何故(我很想解释为什么),在那个 for 循环中所做的引用与确保图像的 URL 实际失败所需的延迟时间并没有很好地混合。
我终于在 another SO thread 上找到了这个绝妙的解决方案:
function ImgError(source){
source.src = "/images/noimage.gif";
source.onerror = "";
return true;
}
<img src="someimage.png" onerror="ImgError(this);"/>
关于javascript - 使用 jquery 在 for 循环中处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11181484/