0

我是 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" > 

我使用 adocument.write来确保至少最终图像存在于我的文件夹中,并且确实存在。我希望看到图像随着循环的进行而循环播放。同样,我没有使用 javascript 的经验,并且根据我认为它的外观将其组合在一起。任何帮助将不胜感激。在此处输入代码

4

2 回答 2

0

我不希望浏览器成为事件驱动的环境,甚至在您返回之前考虑更新屏幕roll()。您需要熟悉setTimeout并将其作为一系列计时器事件进行处理。

于 2012-11-21T08:41:02.843 回答
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;
    }
}
于 2012-11-22T09:21:49.637 回答