2010-09-23 61 views
2

使用下面的代码,我得到一个clock is not defined错误,为什么?x未定义,setTimeout问题

$(function(){ 
    function clock() { 
     var nd = new Date(); 
     var h, m, s; 
     h = nd.getHours(); 
     m = nd.getMinutes(); 
     s = nd.getSeconds(); 
     if (h <= 9) h = "0" + h; 
     if (m <= 9) m = "0" + m; 
     if (s <= 9) s = "0" + s; 
     $('#digital-clock .hour').text(h+':'); 
     $('#digital-clock .min').text(m+':'); 
     $('#digital-clock .sec').text(s); 
    } 
    setTimeout('clock()', 1000); 
}); 

回答

9

因为当你传递一个字符串setTimeout,它里面的代码将在全球范围内的超时时间执行。全球范围内的代码无权访问您拨打setTimeout时出现的任何本地变量。

不要传递字符串到setTimeout,它总是很糟糕(它基本上是推迟的eval,我们都讨厌eval呃?)。相反,使用Function对象:

setTimeout(clock, 1000); 

你可以使用内联函数表达式来创建功能太,例如:

setTimeout(function() { 
    var nd= new Date(); 
    ... 
}, 1000); 
+0

总是要避免的事情总是要避免。 – Pointy 2010-09-23 15:58:23

6

试试这个:

$(function(){ 
    function clock() { 
     var nd = new Date(); 
     var h, m, s; 
     h = nd.getHours(); 
     m = nd.getMinutes(); 
     s = nd.getSeconds(); 
     if (h <= 9) h = "0" + h; 
     if (m <= 9) m = "0" + m; 
     if (s <= 9) s = "0" + s; 
     $('#digital-clock .hour').text(h+':'); 
     $('#digital-clock .min').text(m+':'); 
     $('#digital-clock .sec').text(s); 
    } 
    setTimeout(clock, 1000); 
}); 
0

这有什么错呢?

$(function(){ 
    setTimeout(function() { 
     var nd = new Date(); 
     var h, m, s; 
     h = nd.getHours(); 
     m = nd.getMinutes(); 
     s = nd.getSeconds(); 
     if (h <= 9) h = "0" + h; 
     if (m <= 9) m = "0" + m; 
     if (s <= 9) s = "0" + s; 
     $('#digital-clock .hour').text(h+':'); 
     $('#digital-clock .min').text(m+':'); 
     $('#digital-clock .sec').text(s); 
    }, 1000); 
}); 

除非出于某种原因,您需要稍后引用该功能...?