2011-12-21 68 views
2

我是Javascript的初学者,我在写这段代码时遇到了一些麻烦。它应该为我的网站创建一个数字时钟。简单的时钟不能正常工作

如果你想知道为什么日用消费品是在我的函数/变量名,那是因为它为我的网站的名字:)

另外一个缩写,我正在从萤火虫和我的JSLint NO控制台错误确认我的代码是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。它不适合我。

任何帮助将是伟大的!

回答

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/

+0

哦,谢谢!只是我现在想要的东西:) – Dropped43 2011-12-21 08:26:42