我有一个带滚动功能的骰子应用程序,滚动功能假设在应用程序内滚动骰子,功能正在滚动它们,但它打印出所有骰子相同。这样的事情。 如果我有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();
答案 0 :(得分: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;
}
}