简单时间时钟不起作用,没有错误

时间:2011-12-21 06:22:00

标签: javascript

我是Javascript的初学者,我在编写这段代码时遇到了一些麻烦。它应该为我的网站创建一个数字时钟。

如果您想知道为什么CPGS在我的函数/变量名称中,因为它是我的网站名称的缩写:)

此外,我从FireBug得到没有控制台错误,我的JSLint确认我的代码是vaild。

以下是代码:

    (function() {
    function CpgsClock() {
        this.cpgsTime = new Date();
        this.cpgsHour = this.cpgsTime.getHours();
        this.cpgsMin = this.cpgsTime.getMinutes();
        this.cpgsDay = this.cpgsTime.getDay();
        this.cpgsPeriod = "";
    }

    CpgsClock.prototype.checker = function() {
        if (this.cpgsHour === 0) {
            this.cpgsPeriod = " AM";
            this.cpgsHour = 12;
        } else if (this.cpgsHour <= 11) {
            this.cpgsPeriod = " AM";
        } else if (this.cpgsHour === 12) {
            this.cpgsPeriod = " PM";
        } else if (this.cpgsHour <= 13) {
            this.cpgsPeriod = " PM";
            this.cpgsHour -= 12;
        }
    };

    CpgsClock.prototype.setClock = function() {
        document.getElementById('cpgstime').innerHTML = "" + this.cpgsHour + ":" + this.cpgsMin + this.cpgsPeriod + "";
    };

    var cpgsclock = new CpgsClock();
    setInterval(function() {
        cpgsclock.setClock();
        cpgsclock.checker();
    }, 1000);

})();

所以setClock方法工作正常。但是检查员不会做任何事情。如您所见,它会检查时间并相应地将其设置为AM和PM。它对我没有那样做。

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

您没有更新setInterval ...

中的时钟
CpgsClock.prototype.update = function() {
    this.cpgsTime = new Date();
    this.cpgsHour = this.cpgsTime.getHours();
    this.cpgsMin = this.cpgsTime.getMinutes();
    this.cpgsDay = this.cpgsTime.getDay();
    this.cpgsPeriod = "";
};

在您的setInterval

setInterval(function() {
    cpgsclock.update();
    cpgsclock.checker();
    cpgsclock.setClock();
}, 1000);

jsFiddle:http://jsfiddle.net/qmSua/1/