0

我编写了一个执行掷骰子功能的函数。我在下面给出了代码..但问题出在程序中的某个地方我想比较这两个值并想显示消息。但是为什么它没有发生我没有得到?

function diceroll(){
            var side1 = document.getElementById("side1");
            var side2 = document.getElementById("side2");
            var status = document.getElementById("status");
            var value1 = Math.floor((Math.random() * 6)+ 1);
            var value2 = Math.floor((Math.random() * 6)+ 1);
            var totalvalue = value1 + value2;
            side1.innerHTML = value1;
            side2.innerHTML = value2;
            status.innerHTML ="Dice rolled"+totalvalue+".";

在下面 m 比较两个值并希望显示双侧出现的消息

if(value1 == value2);
  {
    status.innerHTML += "<br/>Got double u can try one more";
  }
}
4

4 回答 4

1
function diceroll(){
            var side1 = document.getElementById("side1");
            var side2 = document.getElementById("side2");
            var status = document.getElementById("status");
            var value1 = Math.floor((Math.random() * 6)+ 1);
            var value2 = Math.floor((Math.random() * 6)+ 1);
            var totalvalue = value1 + value2;
            side1.innerHTML = value1;
            side2.innerHTML = value2;
            status.innerHTML = value1 === value2 ? "Got double u can try one more" :"Dice rolled"+totalvalue+".";
}
于 2013-04-29T11:57:33.467 回答
0
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>
<script type="text/javascript">
    function twoNum()
    {
            var side1 = document.getElementById('txtFirstNumber');
            var side2 = document.getElementById('txtSecondNumber');
            var status = document.getElementById('status');
            var value1 = Math.floor((Math.random() * 6)+ 1);
            var value2 = Math.floor((Math.random() * 6)+ 1);
            var totalvalue = value1 + value2;
            side1.innerHTML = value1;
            side2.innerHTML = value2;
            alert(value1);
            alert(value2);
            status.innerHTML = value1 === value2 ? "Got double u can try one more" :"Dice rolled"+totalvalue+".";
    }
</script>
</head>
<body>
    First Number :<input id="txtFirstNumber" type="text" /><br />
    Second Number:<input id="txtSecondNumber" type="text" />
    <input id="btnAdd" type="button" value="Add" onclick="twoNum();" />
   <div id="status"> </div>
</body>
</html>
于 2013-04-29T12:21:08.793 回答
0

你这里有问题:

if(value1 == value2);
//                  ^
  {
    status.innerHTML += "<br/>Got double u can try one more";
  }

分号表示由 if 条件保护的空语句。下面的块将始终执行,它不属于if- 它被执行为

if (value1 == value2) {
    /*nothing*/;
}
{
    status.innerHTML += "<br/>Got double u can try one more";
}

删除分号,您的代码将起作用:

if (value1 == value2) {
    status.innerHTML += "<br/>Got double u can try one more";
}
于 2013-04-29T12:17:30.577 回答
0

使用 === 等于解决。它比较了 var 的值和类型。谢谢@neo,我删除了一个=。

于 2013-04-29T11:59:35.890 回答