问答详情
源自:8-5 计时器setTimeout()

计时器setTimeout()

<!DOCTYPE HTML>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>计时器</title>

<script type="text/javascript">

  var num=0;

  function startCount() {

    document.getElementById('count').value=num;

    num=num+1;

    setTimeout("startCount()",1000);

  }

  startCount();  //调用函数,为什么没反应???

  

</script>

</head>

<body>

<form>

<input type="text" id="count" />

</form>

</body>

</html>


提问者:木槿111 2017-06-02 14:15

个回答

  • 菜鸟Kira
    2017-06-07 13:24:19
    已采纳

    是因为你的页面还没有加载完就开始调用执行函数,把JS代码挪到下面就可以了

    <!DOCTYPE HTML>

    <html>

    <head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    <title>计时器</title>

    </head>

    <body>

    <form>

    <input type="text" id="count" />

    </form>

    <script type="text/javascript">

      var num=0;

      function startCount() {

        document.getElementById('count').value=num;

        num=num+1;

        setTimeout("startCount()",1000);

      }

      startCount();  //调用函数,为什么没反应???

    </script>

    </body>

    </html>


  • 辣椒加冰
    2017-06-06 11:09:29


    <!DOCTYPE HTML>
    
    <html>
    
    <head>
    
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    
    <title>计时器</title>
    
    <script type="text/javascript">
    
      var num=0;
    
      function startCount() {
    
        document.getElementById('count').value=num;
    
        num=num+1;
    
        setTimeout("startCount()",1000);
    
      }
    
      startCount();  //调用函数,为什么没反应???
    
      
    
    </script>
    
    </head>
    
    <body>
    
    <form>
    
    <input type="text" id="count" />
    
    </form>
    
    </body>
    
    </html>

    你定义的num要写在function()外面,不然运行都是零

  • HappyLei
    2017-06-02 14:38:08

    var a = startCount();