jQuery 和 setTimeout
我有以下代码:
jQuery(document).ready(function()
{
setTimeout($('#loading').fadeIn('slow'), 9999);
});
它应该在 9999 毫秒后慢慢淡入加载元素,但它却立即淡入……为什么?
任何人都可以帮忙。谢谢
I have the following code:
jQuery(document).ready(function()
{
setTimeout($('#loading').fadeIn('slow'), 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为了做你想做的事,你必须将 jQuery 的东西包装在一个匿名函数中:
必须告诉
setTimeout
函数(以及setInterval
)在之后要做什么延迟。只有三种方法可以告诉它要做什么:使用必须
eval
的 JavaScript 字符串:因为这使用了
eval
,并且可能变得非常难看,所以不推荐。但它工作正常。使用函数参考:
请注意,我没有执行
setTimeout(test(), 9999)
。我只是给了它函数的名称。使用您即时构造的匿名函数,这就是我在上面的第一个代码块中所做的。
如果您尝试执行类似
setTimeout(test(), 9999)
的操作,那么浏览器将首先执行test()
,然后给出setTimeout
的返回值。所以在你的尝试中......浏览器正在执行 jQuery 的东西,淡入
#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:
The
setTimeout
function (andsetInterval
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
:Because this uses
eval
, and can get pretty ugly, it's not recommended. But it works fine.With a function reference:
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 tosetTimeout
. So in your attempt......the browser was executing that jQuery stuff, fading in the
#loading
element, and then giving whateverfadeIn
returns tosetTimeout
. As it happens, thefadeIn
function returns a jQuery object. But setTimeout doesn't know what to do with objects, so nothing would happen after the 9999 millisecond delay.settimeout() 函数来自 javascript,并接受一个函数作为参数。
最好的选择是使用 jQuery 的内置 delay() 函数:
更多信息/示例:http://api.jquery。 com/延迟/
The settimeout() function is from javascript and takes a function as an argument.
Best choice would be to use jQuery's builtin delay() function:
More information/exemples: http://api.jquery.com/delay/
setTimeout
接受一个函数作为第一个参数 - 您当前正在传递一个 jQuery 选择器,它会立即被评估并执行fadeIn
操作。相反,传入一个匿名函数:setTimeout
accepts a function as first parameter - you are currently passing a jQuery selector, which immediately gets evaluated which executes thefadeIn
operation. Instead pass in an anonymous function:您还可以使用 jQuery 的 .delay()。
$('#loading').delay(9999).fadeIn('慢');
You can also use jQuery's .delay().
$('#loading').delay(9999).fadeIn('slow');