2012-11-21 57 views
0

我是新來的JavaScript和我試圖創建此循環模擬一些骰子卷。當我點擊滾動時,沒有任何圖像被刷新,並且以顯示的破碎圖像結束。任何人都可以看到我的錯誤在哪裏?Javascript循環更新圖像正在返回破碎的圖像

function roll(){ 
     for(x=0;x<10;x++){ 
      var die_num1 = Math.ceil(Math.random()*6); 
      for(y=0;y<20;y++){ 
       var picturetype1 = Math.ceil(Math.random()*3); 
       if (picturetype1 == 1){prefix1 = "die-";} 
       if (picturetype1 == 2){prefix1 = "dicet-";} 
       if (picturetype1 == 3){prefix1 = "dices-";} 
       document.getElementById("dice").src='http://localhost/CodeIgniter_2.1.2/dice/' + prefix1 + die_num1 + '.gif'; 
      } 
     } 
    } 

體:

<input type ="button" value = "Roll" onclick="roll()" > 
    <img name="dice" id="dice" src="http://localhost/CodeIgniter_2.1.2/dice/die-1.gif" > 

我用document.write,以確保至少在最終圖像我的文件夾中存在,它的作用。我期望在循環過程中看到循環的圖像。同樣,我沒有使用JavaScript的經驗,並根據我認爲應該看起來的方式將它們放在一起。任何幫助會在這裏

+0

的主要原因這不會工作,因爲它只是要快。它不考慮圖像的加載時間。對於人眼而言,它只能看到循環中的最後一幅圖像。 – svenbravo7

+0

謝謝svenbravo。我曾嘗試實施的setTimeout()事件,我想這也許是原因,但我沒有成功有兩種。我將重新創建和更新的問題。 – vizyourdata

回答

0

感謝您讓我朝着正確的方向前進。正如邁克爾所說,我已經重新設計了setTimeout,並且它工作得很好。每次迭代只需要1/10秒,沒有太大的變化,但是完全不同。

function roll2(){ 
    var timer = setTimeout ("roll2();", 100); 
    i++; 
    if(i >= 15) clearTimeout(timer); 
    var die_num1 = Math.ceil(Math.random()*6); 
    var picturetype1 = Math.ceil(Math.random()*3); 
    if (picturetype1 == 1){prefix1 = "die-";} 
    if (picturetype1 == 2){prefix1 = "dicet-";} 
    if (picturetype1 == 3){prefix1 = "dices-";} 
    if (i <=15) { 
     document.getElementById("dice").src='http://localhost/CodeIgniter_2.1.2/dice/' + prefix1 + die_num1 + '.gif'; 
    } 
    if (i >=15) { 
     document.getElementById("dice").src='http://localhost/CodeIgniter_2.1.2/dice/die-' + die_num1 + '.gif'; 
     i=0; 
    } 

}

0

appreciated.enter代碼,我不希望瀏覽器作爲一個事件驅動的環境中,你從你roll()回來之前甚至考慮更新屏幕。您需要熟悉setTimeout並將其作爲一系列計時器事件處理。

+0

我結識了。感謝提示邁克爾! – vizyourdata

+0

不客氣。 –