2010-06-13 36 views
0

我嘗試在改變窗口位置時使用豐富的閃光效果,但存在一個小問題,我無法解決。setTimeout不適用於window.location?

看劇本請

$(document).ready(function(){ 

      $('a.flash').click(function(e) { 
       e.preventDefault(); 
       $('body').fadeOut(1500); 
       setTimeout("", 1500); 
       window.location=this.href; 
      }); 
     }); 

window.location=this.href必須1500毫秒後進行的,但它不會發生。你可以解釋爲什麼嗎? ? 奇怪的是,當我嘗試寫alert("something");而不是window.location=this.href,它工作正常。你能解釋爲什麼嗎?

感謝

+0

爲什麼它在我寫alert()時工作?在這種情況下,它會「睡」1500毫秒,並在警報後。爲什麼? – Simon 2010-06-13 17:51:37

回答

7
$(document).ready(function(){ 

      $('a.flash').click(function(e) { 
       var el = this; 
       e.preventDefault(); 
       $('body').fadeOut(1500); 
       setTimeout(function() { location=el.href }, 1500); 
      }); 
     }); 

你應該提供一個回調函數作爲的setTimeout的第一個參數被後1500毫秒調用。

3

setTimeout不是在其他語言中相當於Thread.sleep(1500);setTimeout安排一段代碼在將來某個時間點運行,並且不會阻止。執行立即通過setTimeout呼叫並繼續。

第一個參數是對函數的引用或將要評估的字符串。

請參閱meder的正確使用方法的答案setTimeout,避免使用匿名函數進行評估。

+0

quotes = eval = badbad,使用lambdas代替 – 2010-06-13 17:47:41

+0

setTimeout(「window.location = this.href;」,1500);不行,我試過了。 但我理解邏輯,謝謝。但爲什麼它工作正常,當我寫alert(); ??? – Simon 2010-06-13 17:49:54

+2

在這種情況下,'this'可能是'window'而不是'a'元素。你有沒有試過我的答案? – 2010-06-13 17:50:27

相關問題