setTimeout and jquery
setTimeout(以及setInterval)必須被告知延時后要做什么,而且只有三種方式來告知它:
1.用一個必須編譯的js的字符串
setTimeout('$("#loading").fadeIn("slow")',9999);?因?yàn)樗ㄟ^編譯會變得相當(dāng)難看,并不推薦. 不過卻很管用.
?
2.帶上一個變量參數(shù)
var test =function(){? ? $('#loading').fadeIn('slow');
};
setTimeout(test,9999);
注意我們不用setTimeout(test(), 9999). 只用這個函數(shù)的名稱.
?
3.用匿名函數(shù),你自己構(gòu)建的,就像我之前在第一個代碼塊中做的那樣.
如果你試圖執(zhí)行類似setTimeout(test(), 9999), 那么瀏覽器會首先執(zhí)行test(),? 再返回值給setTimeout.
所以當(dāng)你試圖...
setTimeout($('#loading').fadeIn('slow'),9999);
...瀏覽器執(zhí)行jquery語句, fading in the #loading?元素, 然后將無論什么?fadeIn?都返回給setTimeout.? 正如它產(chǎn)生的結(jié)果, fadeIn?函數(shù)返回一個jquery對象. 但是setTimeout不知道如何處理對象, 所以在9999毫秒后什么結(jié)果都不會發(fā)生.
?
原文:
http://stackoverflow.com/questions/7085925/jquery-and-settimeout?
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方法來達(dá)到延時目的)
$('#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接受用一個函數(shù)作為第一個屬性 - 你現(xiàn)在通過一個jquery選擇器, 它立即編譯后 執(zhí)行?fadeIn?的操作. 代替入匿名函數(shù))
setTimeout(function(){?$('#loading').fadeIn('slow'),9999);
},9999);
<!------------over GOOD--------------->
?
?
其他參考:
http://www.studyday.net/2011/01/177
轉(zhuǎn)載于:https://www.cnblogs.com/lucoy/archive/2012/04/11/2443129.html
總結(jié)
以上是生活随笔為你收集整理的setTimeout and jquery的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 类型错误
- 下一篇: poj 2528 Mayor's p