jQuery和setTimeout [英] jQuery and setTimeout
问题描述
我有以下代码:
jQuery(document).ready(function()
{
setTimeout($('#loading').fadeIn('slow'), 9999);
});
它应该在9999毫秒后在加载元素中缓慢消失,但是它会立即使其逐渐消失...为什么?
which should slowly fade in the loading element after 9999 miliseconds but instead it fades it in straight away... why?
任何人都可以帮忙.谢谢
Can anyone help. Thanks
推荐答案
要执行所需的操作,您必须将jQuery内容包装在一个匿名函数中:
In order to do what you want, you have to wrap the jQuery stuff in an anonymous function:
setTimeout(function () {
$('#loading').fadeIn('slow');
}, 9999);
必须告知setTimeout
函数(以及setInterval
)在延迟后要做什么.而且只有三种方法可以告诉它怎么做:
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:
-
带有必须
eval
的JavaScript字符串:
With a string of JavaScript that it must
eval
:
setTimeout('$("#loading").fadeIn("slow")', 9999);
因为它使用eval
,并且可能变得很丑陋,所以不建议这样做.但这很好用.
Because this uses eval
, and can get pretty ugly, it's not recommended. But it works fine.
具有功能引用:
var test = function () {
$('#loading').fadeIn('slow');
};
setTimeout(test, 9999);
请注意,我没有执行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.
如果尝试执行类似setTimeout(test(), 9999)
的操作,则浏览器将首先执行test()
,然后将返回值赋予setTimeout
.所以您尝试...
If you try to do something like setTimeout(test(), 9999)
, then the browser will first execute test()
, and then give the return value to setTimeout
. So in your attempt...
setTimeout($('#loading').fadeIn('slow'), 9999);
...浏览器正在执行jQuery内容,使#loading
元素消失,然后将fadeIn
返回的所有内容赋予setTimeout
.碰巧,fadeIn
函数返回一个jQuery对象.但是setTimeout不知道如何处理对象,因此在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.
这篇关于jQuery和setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!