javascript - 使用 jquery 在 for 循环中处理错误

标签 javascript jquery error-handling for-loop

我正在使用 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/

相关文章:

php - 忽略 php 标记错误

javascript - 通过 javascript 访问 Handlebars 变量

javascript - typescript 说: "types ' "a "' and ' "b "' have no overlap".是什么意思?

javascript - 在nodejs中对数组中的相似字符串进行分组

javascript - 如何从 jQuery.find() 结果创建 XMLDocument

javascript - 如何使传单热图上显示的值像这样?

php - PHP禁止第三方库警告

javascript - 我如何从一个catch中抛出一个错误,而不将其变为UnhandledPromiseRejection

javascript - 如何理解这个用 JavaScript 编写的随机颜色函数?

javascript - If else语句,用于更改CSS中的颜色