如何在JS中为变量添加数字?

时间:2014-07-07 12:41:35

标签: javascript html int add var

我一直试图做一个简单的游戏,你尝试将正确的数字作为随机数。如果你赢了,你得到1分。但我无法说明这一点。这就是我所做的:

<html>
<head>
    <title>Luck Game</title>
    <script>
    function onClick(){
        var number = Math.floor(Math.random()*10);
        var usernumber = document.getElementById("input").value ;
        var points = 0;
        document.getElementById("Answer").innerHTML = number ;
        document.getElementById("points").innerHTML = "Points in your account : " + points;
        if(usernumber == number){
            document.getElementById("WIN?").innerHTML = "You WON !. You got 1 point added to your account !";
points = points + 1;

        }
        else{
            document.getElementById("WIN?").innerHTML = "Ow, no luck, you lost..."
        }

    }
    </script>
</head>
<body>
    <input id="input"></input>
    <p id="Answer"></p>
    <button onClick="onClick()"></button>
    <p id="WIN?"></p>
    <p id="points"></p>
</body>

但是&#34;积分=积分+ 1&#34;不管用 ! 怎么了 ?请帮帮我。

3 个答案:

答案 0 :(得分:4)

您应该声明var points外部点击功能。例如:

<script>
var points = 0;
    function onClick(){
        var number = Math.floor(Math.random()*10);
        var usernumber = document.getElementById("input").value ;

        document.getElementById("Answer").innerHTML = number ;
        document.getElementById("points").innerHTML = "Points in your account : " + points;
        if(usernumber == number){
            document.getElementById("WIN?").innerHTML = "You WON !. You got 1 point added to your account !";
points = points + 1;

        }
        else{
            document.getElementById("WIN?").innerHTML = "Ow, no luck, you lost..."
        }

    }
    </script>

因此,计数器将保存在其他地方而不会在每次函数触发时重置。

答案 1 :(得分:1)

您编写它的方式,pointsonClick()函数的本地变量,因此每次调用函数时它都会重置为零。如果您将points的初始化从onClick()中拉出来,那么您将能够安全地增加其值:

<script>
    var points = 0;
    function onClick(){
        var number = Math.floor(Math.random()*10);
        var usernumber = document.getElementById("input").value ;

        document.getElementById("Answer").innerHTML = number ;
        document.getElementById("points").innerHTML = "Points in your account : " + points;
        if(usernumber == number){
            document.getElementById("WIN?").innerHTML = "You WON !. You got 1 point added to your account !";
            points++;
        } else {
            document.getElementById("WIN?").innerHTML = "Ow, no luck, you lost..."
        }
    }
</script>

答案 2 :(得分:1)

在函数外声明var点:

var points = 0;

function onClick(){
    ...
}