麻烦创建"如果那么"用于更改页面背景颜色的Javascript语句

时间:2015-11-24 05:19:15

标签: javascript if-statement random background-color

我现在正在开展一个项目,需要我们使用RNG中内置的Javascripts来生成0-37之间的数字,然后如果数字为奇数则将背景颜色从蓝色更改为黑色,并且蓝色为如果数字是偶数,则为红色。我几乎可以肯定我的命令是正确的,但我仍然无法弄清楚我做错了什么。只是寻找第二组眼睛来浏览它可能会发现我做错了什么。

这是我到目前为止使用的代码: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~

<!DOCTYPE html>
<html>

<script type="text/javascript">

function changeColor () {
    if ( ('wheel' % 2) == 0) {
    document.body.style.backgroundColor = "red";
    }
    else {
    document.body.style.backgroundColor = "black";
}
}

</script>

<body bgcolor="blue">



<p><font size="4" color="white"><b>First place a bet on a number or color. 
<br>Then, spin the wheel to see if you win.</b></font></p>

<button onclick="myFunction()">Spin the Wheel</button>

<font face="Jokerman" color="white" size="6"><p id="wheel"></p></font>

<script>
function myFunction() {
    var x = Math.floor((Math.random() * 38) + 0);
    document.getElementById("wheel").innerHTML = x;
}
</script>

</body>
</html>

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~

页面加载正确,生成数字的按钮工作正常,但无论结果如何,背景颜色都保持蓝色。

3 个答案:

答案 0 :(得分:1)

不,你的“命令”不对。

  1. 在这里,您尝试从简单的JS字符串中获取模数:

    if ('wheel' % 2 == 0) {
    

    实际上会产生NaN,条件总是会产生false

  2. 您已声明并实现了changeColor功能,但实际上您从未调用它。

  3. 为了使其有效,您可以简单地将changeColormyFunction合并 这是工作演示

    function myFunction() {
        var x = Math.floor((Math.random() * 38) + 0);
        document.getElementById("wheel").innerHTML = x;
      
        if (x % 2 == 0) {
          document.body.style.backgroundColor = "red";
        } else {
          document.body.style.backgroundColor = "black";
        }
    }
    body {
      background-color: blue;
    }
    <button onclick="myFunction()">Spin the Wheel</button>
    
    <p id="wheel" style="color: white;"></p>

答案 1 :(得分:0)

更改你的changeColor()方法,如下所示。

 function changeColor() {
        var x = document.getElementById("wheel").innerHTML;

        if ((parseInt(x) % 2) == 0) {
            document.body.style.backgroundColor = "red";
        }
        else {
            document.body.style.backgroundColor = "black";
        }
    }

答案 2 :(得分:0)

您的所有脚本都应该位于页面正文的底部,如此

<!DOCTYPE html>
<html>
<body bgcolor="blue"> 
 <p><font size="4" color="white"><b>First place a bet on a number or color. 
 <br>Then, spin the wheel to see if you win.</b></font></p> 

<button onclick="myFunction()">Spin the Wheel</button>

<font face="Jokerman" color="white" size="6"><p id="wheel"></p></font>

<script>
function myFunction() {
    var x = Math.floor((Math.random() * 38) + 0);
    document.getElementById("wheel").innerHTML = x;
}
</script>
<script type="text/javascript">

function changeColor () {
    if ( ('wheel' % 2) == 0) {
    document.body.style.backgroundColor = "red";
    }
    else {
    document.body.style.backgroundColor = "black";
}
}

</script>
</body>
</html>

凭借我在JS和jQuery方面的技能水平,我可以帮助你。希望它是一个开始!