[Javascript]image物件的onerror事件

  • 5832
  • 0

摘要:[Javascript]image物件的onerror事件

筆記一下~

Image Object的onerror定義:Code is executed when an error occurs with the loading of the image.

舉例說明:
狀況1:有指定src
<image src="test.gif" onerror="alert('This image didn\'t download successfully')" />
如果找不到test.gif這張圖ˇ的話,就會去執行onerror事件。
IE、FF、Chrome都會去執行onerror事件!!

狀況2:沒指定src
<image src="" onerror="alert('This image didn\'t download successfully')" />
結果只有IE、Chrome都會去執行onerror事件,FF沒有去執行!!

 

結論
可以在onerror事件裡面指定如果找不到圖時候使用預設圖,this.src='default.jpg'
並在設計的時候要避免src沒有指定值,以避免FF沒有去執行onerror事件的情形。

 

參考資料:
http://www.javascriptkit.com/jsref/image.shtml