如何使用函数更新变量

时间:2015-06-07 12:02:10

标签: javascript function global local

我无法更新健康变量..我得到一个更新,如果我在功能内部控制它。但它不在外面?

var health;
health = 9;

function scaringCat(event) {
    var catAngry = new Audio("sounds/cat_hiss.mp3");
    catAngry.play();

    health = health -1;
    return health;
}

buttons[1].addEventListener('click', scaringCat);

1 个答案:

答案 0 :(得分:0)

每次都看看这个简单的javascript代码更新健康变量。检查控制台。

<body>

            <input type="button" value="Submit1" onclick="scaringCat()"></input>
            <input type="button" value="Submit2" onclick="scaringCat1()"></input>



<script type="text/javascript">
 var health;
    health = 9;

    function scaringCat() {
    health = health -1;

    console.log(health);
     alert("click on submit2 now!!!")
}

    function scaringCat1() {
    var v=health;
    console.log(v);

    }
    </script>

</body>