setTimeout and jquery
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毫秒后什么結果都不會發生.
?
原文:
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方法來達到延時目的)
$('#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--------------->
?
?
其他參考:
http://www.studyday.net/2011/01/177
轉載于:https://www.cnblogs.com/lucoy/archive/2012/04/11/2443129.html
總結
以上是生活随笔為你收集整理的setTimeout and jquery的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 类型错误
- 下一篇: poj 2528 Mayor's p