-1

我写了一个简单的代码来计算和显示循环计数的数字。
但它不起作用。:(

请告诉我我的问题。

TNX

<html>
<head>
    <script type="text/javascript" src="jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function (){
            function myCount() {
                var count = 0;
                if (count == 0) {
                    count += 1;  
                } else if (count > 10) {
                    count = 0;
                }
                $('.count').text(count);
            }
            setInterval(myCount(),200);
        });        

    </script>
</head>
<body>
    <p>Count form 0 to 10: <span class="count"></span></p>
</body>
</html>
4

3 回答 3

2

请参阅下面代码中的注释并在此处进行操作:http: //jsfiddle.net/dRMrL/

$(document).ready(function () {
    // someone already explained why count has to be declared outside the function
    var count = 0;

    function myCount() {
        // your original if-else wasn't allowing count to increment past 1
        if (count > 10) {
            count = 0;
        }
        $('.count').text(count);
        // increment count regardless of its current value
        count++;
    }

    setInterval(myCount, 500);
});
于 2013-08-30T19:50:06.133 回答
1

将变量放在函数之外,否则您将重新创建变量,并且在启动函数时count始终如此。0

$(document).ready(function () {
    var count = 0;

    function myCount() {
        if (count == 0) {
            count += 1;
        } else if (count > 10) {
            count = 0;
        }
        $('.count').text(count);
    }
    setInterval(myCount, 200);
});
于 2013-08-30T19:11:41.667 回答
1

count每次调用函数时都设置为 0,因此在函数范围之外声明 count 。

$(document).ready(function (){
  var count = 0;
  function myCount() {
    if (count == 0) {
      count += 1;  
    } else if (count > 10) {
      count = 0;
    }
    $('.count').text(count);
  }
  setInterval(myCount,200);
});        
于 2013-08-30T19:12:06.863 回答