[英]Javascript loop to update image is returning broken image
我是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的經驗,並且已根據我的想法將其組合在一起。 任何幫助將不勝感激。在此處輸入代碼
我不希望瀏覽器成為事件驅動的環境,甚至不會考慮在您從roll()
返回之前更新屏幕。 您需要熟悉setTimeout
並將其作為一系列計時器事件進行處理。
感謝您為我設定正確的方向。 我已經按照Michael的建議對它進行了重新設計,以使用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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.