2010-09-23 59 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); 
}); 

除非出於某種原因,您需要稍後引用該功能...?