簡體   English   中英

JavaScript 減法 function 不能正常工作

[英]JavaScript substraction function not working properly

我做了一個簡單的 html 和 JS 點擊計數器網站,但我無法讓減號 function 工作。 這是我的代碼:

 <.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>

只有較低的計數按鈕不起作用。 有人可以幫我告訴我是否遺漏了什么嗎?

您需要在add方法之外定義counter

[編輯] 您在 function 中定義了計數器變量,因此只能從 function 內部訪問它。 通過將其移到外部,每個 function 都可以訪問(並修改)該變量。

 <.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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM