开发者

Using setTimeout() in jquery

I'm not new to Javascript but then I realize I don't know how to use setTimeout().

I have trie开发者_运维问答d this:

$(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>
  }
})

Can anyone help me with this one?


Pass a reference to the changeit function instead of a string of JavaScript code.

$(document).ready(function() {
    setTimeout(changeit, 1000);
    function changeit() {
        $("#hello").html("Hello world - this was inserted using jQuery.");
    }
});


How about:

setTimeout(changeit, 1000);


Do this:

$(function() {
  setTimeout(changeit, 1000);
});

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

or this:

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

The problem with your version is that you're passing a string to setTimeout() which is eval'ed but by that time changeit() is out of scope so it won't work.

The alternative is to make changeit global (as per the first code snippet).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜