javascript计数器不会在每次调用中增加计数器

时间:2016-07-19 16:12:54

标签: javascript

在javascript代码中,我希望这个函数每次调用时都应该递增计数器,但是每次调用它时值都保持不变,即为1 ..为什么它不递增。

 <body>
        <p>increasing the counter</p>
        <button type = "button" onclick="document.getElementById('para').innerHTML = add()">Counter</button>
        <p id = "para"></p>

    <script>
      function add(){
            var counter = 0;
            return counter = counter + 1;
           }
    </script>
 </body>

5 个答案:

答案 0 :(得分:1)

全局定义counter(在函数外部)或者每次调用函数时,counter的值都设置为0

&#13;
&#13;
var counter = 0;

function add() {
  return counter = counter + 1; //OR return ++counter;
}
&#13;
<p>increasing the counter</p>
<button type="button" onclick="document.getElementById('para').innerHTML = add()">Counter</button>
<p id="para"></p>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您需要将counter变量置于函数定义之外(即将其定义为全局变量),以便保留其先前的值。否则每次调用该函数时,其值都将重置为0.

<body>
        <p>increasing the counter</p>
        <button type = "button" onclick="document.getElementById('para').innerHTML = add()">Counter</button>
        <p id = "para"></p>

    <script>
      var counter = 0;
      function add(){
            return counter = counter + 1;
           }
    </script>
 </body>

答案 2 :(得分:0)

counter在每次通话中都会重新设置为0

在这种情况下,计数器可以移动到函数之外:

var counter = 0;
function add(){
    return counter = counter + 1;
}
        <p>increasing the counter</p>
        <button type = "button" onclick="document.getElementById('para').innerHTML = add()">Counter</button>
        <p id = "para"></p>

答案 3 :(得分:0)

Slightly alter program    
<html>
    <body>
    <script>
    var counter = 0;

    function add() {
      return counter = counter + 1;
    }
    </script>
    <p>increasing the counter</p>
    <button type="button" onclick="document.getElementById('para').innerHTML = add

    ()">Counter</button>
    <p id="para"></p>
     </body>
    </html>

答案 4 :(得分:0)

add()函数中声明add()。每次调用counter = 0时,计数器都会设置为ZERO return counter = counter + 1,然后在递增1 var counter = 0; function add (){ return counter = counter + 1; }后返回。

&#13;
&#13;
        <p>increasing the counter</p>
        <button type = "button" onclick="document.getElementById('para').innerHTML = add()">Counter</button>
        <p id = "para"></p>
&#13;
var counter
&#13;
&#13;
&#13;

第二种方法,如果要在add()中声明var add = (function (){ var counter = 0; return function() {return counter = counter + 1;} })();(以避免污染全局范围),请使用JS闭包。请参阅以下代码段。

&#13;
&#13;
        <p>increasing the counter</p>
        <button type = "button" onclick="document.getElementById('para').innerHTML = add()">Counter</button>
        <p id = "para"></p>
&#13;
<div class="cbody">
<?php include("head.html");?>
<div style="float: right;">
<a href="target.php"><img src="assets/img/target.jpg"></a>
</div>
<div style="float: left;">
<a href="target2.php"><img src="assets/img/target2.jpg"></a>
</div></div>
&#13;
&#13;
&#13;