2012-06-24 22 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