2016-03-14 18 views
0

我正在寫一個網頁,並期待每秒在自己的目錄中自動刷新圖像。我寫了代碼,但我不知道爲什麼它不起作用。使用javascript自動清理HTML中的圖像

<html> 

<SCRIPT language="JavaScript" type="text/javascript"> 
var t = 1 // Interval in Seconds 
images = new Array('foo.png'); //URLs of the Images 

function Start() { 
tmp = new Date(); 
tmp = "?"+tmp.getTime(); 
for (i=1;i<image.length;i++){ 
document.getElementById("img"+i).src = images[i]+tmp; 
} 
setTimeout("Start()", t*1000) 
} 
Start(); 
</SCRIPT> 

<body> 
<IMG src="foo.png" border="1" name="refresh" id="img1"> 

</body> 
</html> 

回答

0

的問題是,數組索引從0開始不是從1,你的循環變量,從1開始,但陣列在索引0只有1項,那麼images[1]將返回undefined。

var t = 1 // Interval in Seconds 
images = new Array('foo.png'); //URLs of the Images 

function Start() { 
    var tmp = "?" + new Date().getTime(); 
    for (var i = 0; i < image.length; i++) { 
    document.getElementById("img" + (i + 1)).src = images[i] + tmp; 
    } 
    setTimeout("Start()", t * 1000) 
} 
Start(); 
+0

我明白了錯誤,但代碼似乎仍不是我想working..The測試案例: 創建一個index.html文件並保存問題中的內容,在chrome中打開index.html,然後進入該目錄並刪除foo.png。但foo.png仍然顯示在我的Chrome – user3121369

+0

Hi @ user3121369,我認爲這個問題是由於瀏覽器緩存。你可以強迫它不要做,通過添加meta標籤(例如 )。登錄論壇https://www.sitepoint.com/community/t/how-to-force-the-users-browser-to-clear-its-cache/18631 –

0

正如@Arun P Johny所述,數組索引從零開始。

您在for循環中使用了i<image.length,但您的var名稱爲images,請注意額外的s

由於i開始從0值,設置<img>idimg0

<html> 

<SCRIPT language="JavaScript" type="text/javascript"> 
var t = 1 // Interval in Seconds 
images = new Array('foo.png'); //URLs of the Images 

function Start() { 
tmp = new Date(); 
tmp = "?"+tmp.getTime(); 
for (i=0;i<images.length;i++){ 
document.getElementById("img"+i).src = images[i]+tmp; 
} 
setTimeout(Start, t*1000) 
} 
Start(); 
</SCRIPT> 

<body> 
<IMG src="foo.png" border="1" name="refresh" id="img0"> 

</body> 
</html>