jQuery和setTimeout [英] jQuery and setTimeout

查看:62
本文介绍了jQuery和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:

  1. 带有必须eval的JavaScript字符串:

  1. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆