2015-07-09 36 views
0

出於某種原因,我的photo.onerror圖像沒有加載,因爲我通過圖像選項卡並遇到一個沒有設置,onerror圖像仍然不會加載,請參閱這有什麼不對?如何用新圖像替換onerror src圖像

if (document.getElementById("draft_player_photo")) { 
    var photo = document.getElementById("draft_player_photo"); 
    photo.src = "http://www.myfantasyleague.com/player_photos_2013/" + pid + "_thumb.jpg"; 
    photo.alt = playerDatabase['pid_' + pid].name; 
    photo.title = playerDatabase['pid_' + pid].name; 
    photo.onerror = "this.onerror=null;this.src='http://www.myfantasyleague.com/player_photos_2010/no_photo_available.jpg';"; 
    } 
+1

這不是jQuery的旁路。 – Turnip

+0

難道你不能只遍歷所有具有該ID的圖像,並將每個的src設置爲你想要的那個? –

+0

你在嘗試這樣的事情嗎? http://jsfiddle.net/kn816rr1/ – Sushil

回答

1

您需要定義photo.onerror的功能,你現在要做的,你只要指定一個字符串onerror

.. 
photo.onerror = function() { 
    this.src=this.getAttribute('fallback') //reuse of my original idea, but whatever works 
} 
... 

演示 - >http://jsfiddle.net/zpLm0e7d/


我將執行回退src

<img id="draft_player_photo" fallback="http://www.w3schools.com/images/colorpicker.gif"src="http://www.myfantasyleague.com/player_photos_2013/11657_thumb.jpg" alt="this image"> 

然後捕捉任何onerror並設置src到回退值:

$('img').on('error', function() { 
    $(this).attr('src', $(this).attr('fallback')) 
}); 

演示 - >http://jsfiddle.net/4p8gdppL/

Sry基因爲w3fools參考,它們與短的長度的圖像。