【问题标题】:Program not functionning [closed]程序不起作用[关闭]
【发布时间】:2017-04-22 10:15:17
【问题描述】:

我还是 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>

【问题讨论】:

    标签: javascript onclick innerhtml


    【解决方案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 在创建它们的函数作用域之后不再存在。

    【讨论】:

      【解决方案2】:

      这段代码:

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

      不在函数内部

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

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

      您永远不会再次比较这些值。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-23
        • 2019-11-25
        • 1970-01-01
        • 2015-02-04
        • 1970-01-01
        相关资源
        最近更新 更多