2012-06-24 19 views
0

我正在使用for循环向用户显示一系列缩略图。如果thumbnails[i].path无法加载,我想加载thumbnail_unavailable.jpg代替它。使用jquery处理for循环中的错误

据我所知,jQuery的.error() handeler应该如下使用。

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

回答

0

我什么都试过,包括on/one绑定处理失败的资源。不知何故(并且我很喜欢关于为什么的解释),在for循环中所做的引用并没有很好地与延迟时间混合,以确保图像的URL实际上失败。

我终于找到了another SO thread这个光辉的解决方案:

function ImgError(source){ 
    source.src = "/images/noimage.gif"; 
    source.onerror = ""; 
    return true; 
} 

<img src="someimage.png" onerror="ImgError(this);"/> 
+0

你大概应该在这种情况下,作为重复杀了你自己的问题。 – tomdemuyt

+0

@tomdemuyt,你看过那个帖子吗?相同的解决方案,不同的问题(第二个最高票数的响应是该OP的可行解决方案,但不适用于此线程中的代码示例)证明了这一点。但是更多的技术说明:直到最后两个人撤回答案,我才被允许关闭此线程。 – Kyle