2011-12-21 64 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