代码之家  ›  专栏  ›  技术社区  ›  Reigel Gallarde

在jquery中使用setTimeout()

  •  2
  • Reigel Gallarde  · 技术社区  · 16 年前

    我对Javascript并不陌生,但后来我意识到我不知道如何使用它 setTimeout() .

    我试过这个:

    $(document).ready(function(){
    
      setTimeout('changeit()',1000); // I have also tried setTimeout('changeit',1000);
      // var t = setTimeout('changeit()',1000); <--- tried also something like this.
    
      // changeit(); <-- works when i do this.
    
      function changeit(){
        $('#hello').html('Hello World - this was inserted using jQuery');
        // #hello is <p id="hello">Hello World</p>
      }
    })
    

    有人能帮我做这个吗?

    3 回复  |  直到 13 年前
        1
  •  4
  •   icktoofay pcp    16 年前

    将引用传递给 changeit

    $(document).ready(function() {
        setTimeout(changeit, 1000);
        function changeit() {
            $("#hello").html("Hello world - this was inserted using jQuery.");
        }
    });
    
        2
  •  1
  •   Matchu    16 年前

    怎么样:

    setTimeout(changeit, 1000);
    
        3
  •  1
  •   cletus    16 年前

    这样做:

    $(function() {
      setTimeout(changeit, 1000);
    });
    
    function changeit() {
      $('#hello').html('Hello World - this was inserted using jQuery');
    }
    

    $(function() {
      setTimeout(changeit, 1000);
      function changeit() {
        $('#hello').html('Hello World - this was inserted using jQuery');
      }
    });
    

    您的版本存在的问题是,您正在将字符串传递给 setTimeout() 这是经过评估的,但到那时 changeit() 超出范围,因此无法工作。

    另一种选择是 changeit 全局(根据第一个代码段)。