如何使用setInterval计算0到10

时间:2013-08-30 19:09:08

标签: jquery html count setinterval

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

请告诉我我的问题。

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>

3 个答案:

答案 0 :(得分: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);

    });

答案 1 :(得分: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);
});

答案 2 :(得分: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);
});