setTimeout(以及setInterval)必须被告知延时后要做什么,而且只有三种方式来告知它:
1.用一个必须编译的js的字符串
setTimeout('$("#loading").fadeIn("slow")',9999);
因为它通过编译会变得相当难看,并不推荐. 不过却很管用.
2.带上一个变量参数
var test =function(){ $('#loading').fadeIn('slow'); }; setTimeout(test,9999);
注意我们不用setTimeout(test(), 9999)
. 只用这个函数的名称.
3.用匿名函数,你自己构建的,就像我之前在第一个代码块中做的那样.
如果你试图执行类似setTimeout(test(), 9999)
, 那么浏览器会首先执行test()
, 再返回值给setTimeout
.
所以当你试图...
setTimeout($('#loading').fadeIn('slow'),9999);
...浏览器执行jquery语句, fading in the #loading
元素, 然后将无论什么 fadeIn
都返回给setTimeout
. 正如它产生的结果, fadeIn
函数返回一个jquery对象. 但是setTimeout不知道如何处理对象, 所以在9999毫秒后什么结果都不会发生.
原文:
In order to do what you want, you have to wrap the jQuery stuff in an anonymous function:
setTimeout(function(){ $('#loading').fadeIn('slow'); },9999);
The setTimeout
function (and setInterval
as well) must be told what to do after the delay. And there are only three ways to tell it what to do:
-
With a string of JavaScript that it must
eval
:setTimeout('$("#loading").fadeIn("slow")',9999);
Because this uses
eval
, and can get pretty ugly, it's not recommended. But it works fine. -
With a function reference:
var test =function(){ $('#loading').fadeIn('slow'); }; setTimeout(test,9999);
Note that I didn't do
setTimeout(test(), 9999)
. I just gave it the name of the function. -
With an anonymous function that you construct on the fly, which is what I did in the first code block above.
If you try to do something like setTimeout(test(), 9999)
, then the browser will first executetest()
, and then give the return value to setTimeout
. So in your attempt...
setTimeout($('#loading').fadeIn('slow'),9999);
...the browser was executing that jQuery stuff, fading in the #loading
element, and then giving whatever fadeIn
returns to setTimeout
. As it happens, the fadeIn
function returns a jQuery object. But setTimeout doesn't know what to do with objects, so nothing would happen after the 9999 millisecond delay.
/*** 解决方案: ***/
You can also use jQuery's .delay(). (可用一下jquery方法来达到延时目的)
$('#loading').delay(9999).fadeIn('slow');
<!------------or--------------->
setTimeout
accepts a function as first parameter - you are currently passing a jQuery selector, which immediately gets evaluated which executes the fadeIn
operation. Instead pass in an anonymous function: (setTimeout接受用一个函数作为第一个属性 - 你现在通过一个jquery选择器, 它立即编译后 执行 fadeIn
的操作. 代替入匿名函数)
setTimeout(function(){ $('#loading').fadeIn('slow'),9999); },9999);
<!------------over GOOD--------------->
其他参考: