2013-06-01 35 views
1

我處於一種情況,我知道圖像的名稱,但不是確切的擴展名。擴展名可以是.jpg或.png。此外,圖像本身可能不存在。所以,我必須執行以下操作:HTML:觸發onerror兩次以顯示替代圖像的替代

  1. 嘗試加載image.jpg的
  2. ONERROR,試圖加載image.png
  3. ONERROR,顯示notfound.jpg

我寫以下代碼:

<img src=image.jpg onerror="this.onerror=null; this.src=image.png;"> 

但是「this.onerror = null」只會停止進入無限循環的錯誤。當再次觸發onerror時,如何加載替代圖像「notfound.jpg」的替代方法?

+0

你可以使用jQuery嗎? –

回答

0

在這裏,我有我會使用jQuery的。我問你是否可以,你沒有回覆。

所以它就是這樣。

這裏將是標準的HTML:

<img src=image.jpg alt="" /> 

這裏將jQuery的連接到它:

$('img').on('error', function() { 
    var $this = $(this); 
    // ajax with type 'HEAD' checks to see if the file exists 
    $.ajax({ 
     url: 'image.png', //place alternate img link here 
     type: 'HEAD', 
     success: function() { 
      //if success place alternate image url into image 
      $this.prop('src', 'image.png'); 
     }, 
     error: function() { 
      //if error place notfound image url into image 
      $this.prop('src', 'notfound.jpg'); 
     } 
    }); 
}); 

在這裏,我有它在不同的環境中工作,但它顯示了終端產品: http://jsfiddle.net/6nFdr/

+0

謝謝!我試圖避免jquery,但似乎這是唯一的選擇。 – mrclutch31

0

onerror設置圖像src後返回false。

例如:

<img src="fake.png" onerror="this.src='http://www.gravatar.com/avatar/9950cb3a6bdc0e10b1260135bd145e77?s=32&d=identicon&r=PG'; return false;"> 

演示:http://jsfiddle.net/rlemon/SKtVg/

你應該避免內聯JavaScript順便說一句。不是說這是不正確的,只是不太需要。 如果你沒有使用內聯js,你可能只會有一個小函數來檢查其他圖像,如果它們沒有加載顯示已知存在的圖像。

+0

你能解釋這是如何幫助嗎?如何顯示「notfound.jpg」? – mrclutch31