【问题标题】:javascript for loop to use a function for several objectsjavascript for循环为多个对象使用一个函数
【发布时间】:2014-09-14 07:54:56
【问题描述】:

我正在开发一款游戏,该游戏具有三个骰子立方体,在单击按钮时会显示随机面孔。 图像由 css 图像精灵提供。如果随机数为 1,则将骰子立方体分配给具有其图像精灵的 css 类。

function diceroll (){

    var randomnumber = Math.floor(Math.random() * (6 - 1 + 1)) + 1;

        switch (randomnumber) {

        case 1:
            document.getElementById("dice1").setAttribute("class", "face1");
            break;
        case 2:
            document.getElementById("dice1").setAttribute("class", "face2");
            break;
        case 3:
            document.getElementById("dice1").setAttribute("class", "face3");
            break;
        case 4:
            document.getElementById("dice1").setAttribute("class", "face4");
            break;
        case 5:
            document.getElementById("dice1").setAttribute("class", "face5");
            break;
        case 6:
            document.getElementById("dice1").setAttribute("class", "face6");
            break;
    }
}

我有一个单独的按钮,当点击它应该运行上面的 diceroll 函数到 id 为 dice1、dice2 和 dice3 的三个 div。

我想用

function gotoloop (){

    for (i = 0; i < 2; i++) {
        // the code that affects dice(n) and n=1 and then diceroll function
        // affects dice1 n+1
    }

}

我进行了研究,但找不到实现最后注释两行代码的方法。请让我知道我的方法是否正确并帮助我编写代码。

【问题讨论】:

  • 各位,请解释您的反对票。这个问题可能不是最好的,因为问题很简单,但它写得很清楚并且显示了一些工作。

标签: javascript html css loops for-loop


【解决方案1】:

如果我正确理解了你的问题,你想要这样的东西:

function diceroll (diceId){

    var randomnumber = Math.floor(Math.random() * 6) + 1;

    switch (randomnumber) {

        case 1:        document.getElementById(diceId).setAttribute("class", "face1");        break;
        case 2:        document.getElementById(diceId).setAttribute("class", "face2");        break;
        case 3:        document.getElementById(diceId).setAttribute("class", "face3");        break;
        case 4:        document.getElementById(diceId).setAttribute("class", "face4");        break;
        case 5:        document.getElementById(diceId).setAttribute("class", "face5");        break;
        case 6:        document.getElementById(diceId).setAttribute("class", "face6");        break;
    }
}

function gotoloop (){
    // Start loop at i=1 because the first ID is dice1
    for (var i = 1; i <= 3; i++) {
        // the code that affects dice(n) and n=1 and then diceroll function affects dice1
        // n+1
        diceroll("dice" + i);
    }
}

或者根据 Marc Baumbach 的评论,您可以这样写:

function diceroll (diceId){

    var randomnumber = Math.floor(Math.random() * 6) + 1;

    document.getElementById(diceId).setAttribute("class", "face" + randomnumber);
}

【讨论】:

  • +1,我想这就是他们的意思。 switch 也可以删除,只需将随机数附加到"face" 字符串。这里的代码(6 - 1 + 1) 也应该只是6。 :)
猜你喜欢
  • 2014-11-29
  • 1970-01-01
  • 2021-02-27
  • 2021-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-06
相关资源
最近更新 更多