程序无法运行

时间:2017-04-22 10:15:17

标签: javascript onclick innerhtml

我还是JavaScript新手。我正在尝试制作一个包含2个按钮的程序,单击一个按钮后,它会创建一个随机数。

问题在于,当我试图比较它们时,它并没有显示哪一个更大。首先,我认为问题在于变量不是全局的,但它没有改变任何东西。

有人可以帮我找到问题吗?

以下是 JavaScript 代码:

var par1 = document.getElementById("para1");
var par2 = document.getElementById("para2");
var winner = document.getElementById("win");
 
function button1() {
    num1 = Math.floor(Math.random() * 7);
    par1.innerHTML = num1;
}
 
function button2() {
    num2 = Math.floor(Math.random() * 7);
    par2.innerHTML = num2;
}
if (num1 > num2) {
    winner.innerHTML = "the winner is player 1";
} else {
    winner.innerHTML = "the winner is player 2";
}
<!DOCTYPE html>
<html>
 
<head>
    <meta charset="utf-8">
    <title>dicestimulator</title>
    <link rel="stylesheet" href="dicestimulator.css">
</head>
 
<body>
    <div class="container">
        <div>
            <h1>Player1</h1>
            <button type="button" name="button1" onclick="button1()" id="but1">roll 
    dice</button>
            <p id="para1">Click the button to see what you get</p>
        </div>
        <div>
            <h1>Player2</h1>
            <button type="button" name="button2" id="but2" onclick="button2()">roll 
     dice</button>
            <p id="para2">Click the button to see what you get</p>
        </div>
        <p id="win">let's see who wins!!!</p>
        <script src="dicestimulator.js"></script>
    </div>
</body>
 
</html>

2 个答案:

答案 0 :(得分:1)

代码部分:

if(num1>num2){
winner.innerHTML="the winner is player 1";
}else{
winner.innerHTML="the winner is player 2";
}

... 不在函数中。

它在最初加载脚本时运行。

稍后,您调用button1button2函数。这些更改了num1

的值

您永远不会再次比较

如果要在button1button2函数运行时进行比较,则需要在这些函数调用时调用代码。

答案 1 :(得分:1)

if(num1>num2){
winner.innerHTML="the winner is player 1";
}else{
winner.innerHTML="the winner is player 2";
}

您没有在HTML代码中的任何位置调用上述块。

我的解决方案是制作第三个调用函数getwinner

的按钮
function getWinner() {
if(par1.val>par2.val){
winner.innerHTML="the winner is player 1";
} else{
winner.innerHTML="the winner is player 2";
}
}

请注意,您无法调用在这些函数之外的函数中创建的局部变量。 num1和num2在创建它们的函数的范围之后不再存在。