2011-12-12 137 views
2

我使用以下代碼刷新瀏覽器中的圖像。我只想修改代碼,以便首先檢查圖像是否存在,然後顯示圖像。如果圖像不存在,我只會將圖像刷新爲圖像的前一版本。有人能指出我如何使用javascript或jquery完成此操作嗎?檢查圖像是否存在

<html> 
    <head> 
     <script language="JavaScript"> 
      function refreshIt(element) { 
       setTimeout(function() { 
        element.src = element.src.split('?')[0] + '?' + new Date().getTime(); 
        refreshIt(element); 
       }, 500); // refresh every 500ms 
      } 
     </script> 
    </head> 
    <body> 
     <img src="swt.png" name="myCam" onload="refreshIt(this)"> 
    </body> 
</html> 

編輯:我需要一個已經實現的功能加上文件檢查的組合。

功能:

if image exist 
    refresh image 
else 
    show cached image 

回答

3

事情是這樣的:

 
$('#image_id').error(function() { 
    alert('Image does not exist !!'); 
}); 

+0

我可以結合我已經與這個實現的功能? – glarkou

+0

這不會按原樣工作(demo:http://jsfiddle.net/davidThomas/jXWS7/),使用這個你必須用jQuery設置src屬性,然後鏈接'error() '方法:http://jsfiddle.net/davidThomas/jXWS7/1/ –

+0

是的,但我仍然想要一種方法來設置超時以更新圖片.. – glarkou