曾經利用判斷圖的height和width來判斷圖片是否存在。
但那是個不好的做法。
常常會發現圖明明好好的,但是width或height老是偵測錯誤。
近幾天在網路上找到一個好方法,既簡單又快速。
以下是範例程式:
當然,以上是最原始,最笨的寫法。可以改成用jQuery來偵測某一區塊(block)的圖檔,這就看你要怎麼去發揮了。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
</head> | |
<body> | |
<img src="http://pics.blog.yam.com/badimage.jpg" /> | |
<script> | |
function hi(){ | |
var i=new Image(); | |
i.onerror=function(){alert('error and do something');}; | |
i.src="http://pics.blog.yam.com/badimage.jpg"; | |
} | |
</script> | |
<input type='button' value="test" onclick="hi();" /> | |
</body> | |
</html> |