2010-06-13 72 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

相关问题