2015-01-08 67 views
2

我有這樣的代碼:(剝離片質疑不相關)函數沒有定義?

$(function() { 

mins = 0; //Set the number of minutes you need 
//secs = 0; 

    function Decrement(mins){ 
     var secs = mins * 60; 
     var currentSeconds = 0; 
     var currentMinutes = 0; 
     if(currentSeconds <= 9){ currentSeconds = "0" + currentSeconds; } 
     secs--; 
     document.getElementById("commercial").innerHTML = "Please wait "+currentMinutes + ":" + currentSeconds; //Set the element id you need the time put into. 
     if(secs !== -1){ alert("Done!"); } 
    } 

    function runCommercial(time){ 
     $('#commercial').html('Plase wait 8:00'); 
     $('#commercial').attr("disabled", "disabled"); 
     mins = 8; 
     setInterval('Decrement(8)',1000); 
    } 

    $('#commercial').click(function(){ 
    runCommercial(30); 
    }); 
}); 

每當我點擊的商業按鈕,按鈕上的文字被設置爲8:00,因爲它應該altough也不會倒計時,相反,它給了我在Firefox的開發控制檯「Decrement()沒有定義」。爲什麼會發生這種情況,我該如何解決?

謝謝。

回答

7

發生這種情況,因爲字符串'Decrement(8)'正在eval在全局命名空間uated,而不是在你的IIFE關閉。

變化

setInterval('Decrement(8)',1000); 

setInterval(function() {Decrement(8);}, 1000); 

它被認爲不好的做法,導致代碼eval式的解釋,嘗試總是傳遞函數爲的setTimeout的setInterval

+0

我還會補充說,如果遞減不需要參數(8)。你可以調用setInterval(Decrement,1000); – Buck3y3