未定义函数

Function is not defined?

本文关键字:函数 未定义      更新时间:2023-09-26

我有这个代码:(与问题无关的剥离片段)

$(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,尽管它不会倒计时,而是在 Firefox 的开发控制台中给我"Decrement() 未定义"。为什么会发生这种情况,我该如何解决?

谢谢。

发生这种情况是因为字符串'Decrement(8)'在全局命名空间中eval使用,而不是在您的 IIFE 闭包下。

改变

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

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

导致代码的eval式解释,尝试始终将函数传递到 setTimeoutsetInterval 等被认为是不好的做法。