JavaScript减法功能无法正常工作

我做了一个简单的HTML和JS点击计数器网站,但是我无法使用减号功能。 这是我的代码:

<!DOCTYPE html>
<html>
    <head>
        <title>
            Tally Counter
        </title>
        <Link rel='stylesheet' href='style.css'>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>></script>
        <script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
        <script type="text/javascript" src="http://s3.amazonaws.com/codecademy-content/courses/hour-of-code/js/alphabet.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script>
            var add = (function(){
                var counter = 0;
                return function (){return counter+=1;}
            })();
            function addCount(){
                document.getElementById("carrier").innerHTML = add();
            }
            var minus = (function(){
                return function (){return counter-=1;}
            })();
            function minusCount(){
                document.getElementById("carrier").innerHTML = minus();
            };
        </script>
    </head>
    <body>
        <h1>
            Counter
        </h1>
        <p id='carrier'> 0 </p>
        <button onclick="addCount()">Add count</button>
        <button onclick="minusCount()">Lower count</button>
    </body>
</html>

仅小数计数按钮不起作用。有人可以帮忙告诉我是否缺少什么吗?

评论
wearum
wearum

You need to define counter outside your add method.

<!DOCTYPE html>
<html>
    <head>
        <title>
            Tally Counter
        </title>
        <Link rel='stylesheet' href='style.css'>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>></script>
        <script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
        <script type="text/javascript" src="http://s3.amazonaws.com/codecademy-content/courses/hour-of-code/js/alphabet.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script>
            var counter = 0; // here
            var add = (function(){
                // var counter = 0; // not here
                return function (){return counter+=1;}
            })();
            function addCount(){
                document.getElementById("carrier").innerHTML = add();
            }
            var minus = (function(){
                return function (){return counter-=1;}
            })();
            function minusCount(){
                document.getElementById("carrier").innerHTML = minus();
            };
        </script>
    </head>
    <body>
        <h1>
            Counter
        </h1>
        <p id='carrier'> 0 </p>
        <button onclick="addCount()">Add count</button>
        <button onclick="minusCount()">Lower count</button>
    </body>
</html>
点赞
评论