0

我有一个带有滚动功能的骰子应用程序,滚动功能假设在应用程序内滚动骰子,该函数正在滚动它们,但它打印出所有骰子都是一样的。像这样的东西。如果我有 4 个有价值的骰子

1-4-7-3,当我掷骰子时,答案将是随机的 nr,比如说 6,然后所有 6 个骰子输出 6-6-6-6。

尖端 ?

  function rollEvent(){ 
        var rollDices = "roll"; 
        var addClass= document.getElementsByClassName(rollDices); 
        addClass=addClass[addClass.length-1]; 
        addClass.addEventListener("click", rollDice, true); 
        var diceArray = Array=[ 
        "dice dice-side-one", 
        "dice dice-side-two", 
        "dice dice-side-three", 
        "dice dice-side-four", 
        "dice dice-side-five", 
        "dice dice-side-six"]; 
        function rollDice(e) { 
            var name = diceArray[Math.floor(Math.random() * diceArray.length)]; 
            var obj=e.target; 
            var elementToRemove = " dice-window-wrapper "; 
            while((" "+obj.className+" ").indexOf(elementToRemove)==-1){ 
                obj=obj.parentNode; 
            } 

            var allDiceInWindow=obj.getElementsByClassName("dice"); 


             for(var i = 0; i<allDiceInWindow.length; i++){

                  allDiceInWindow[i].className = name;

            }



        } 
    }
    rollEvent();
4

1 回答 1

1

您只调用Math.random()一次该方法,然后将结果应用于所有骰子。试试这个rollDice方法:

function rollDice(e) { 
    var obj=e.target; 
    var elementToRemove = " dice-window-wrapper "; 
    while((" "+obj.className+" ").indexOf(elementToRemove)==-1){ 
        obj=obj.parentNode; 
    }
    var allDiceInWindow=obj.getElementsByClassName("dice"); 

    for(var i = 0; i<allDiceInWindow.length; i++){
        // set the name individually for each die
        var name = diceArray[Math.floor(Math.random() * diceArray.length)]; 
        allDiceInWindow[i].className = name;
    }
} 
于 2013-02-09T09:57:07.503 回答