<span id="clock" style="font-size:14px;"></span>
$(document).ready(function() {
showTime();
});
function showTime() {
var week = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];
var now = new Date();
var h = now.getHours(), m = now.getMinutes(), s = now.getSeconds();
h = h < 10 ? "0" + h : h;
m = m < 10 ? "0" + m : m;
s = s < 10 ? "0" + s : s;
$("#clock").html('當前時間:' + now.toLocaleDateString() + " " + week[now.getDay()] + " " + h + ":" + m + ":" + s);
setTimeout(showTime, 1000);
}
function Clock() {
var date = new Date();
this.year = date.getFullYear();
this.month = date.getMonth() + 1;
this.date = date.getDate();
this.day = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"][date.getDay()];
this.hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
this.minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
this.second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
this.toString = function() {
return "現在時間是:" + this.year + "年" + this.month + "月" + this.date + "日 " +
this.hour + ":" + this.minute + ":" + this.second + " " + this.day;
};
this.display = function(ele) {
var clock = new Clock();
ele.html(clock.toString());
setTimeout(function() { clock.display(ele); }, 1000);
};
}
// 使用
$(document).ready(function() {
var clock = new Clock();
clock.display($("#clock"));
});
| 特性 | 方式一 | 方式二 |
|---|---|---|
| 代碼風格 | 過程式 | 面向對象 |
| 擴展性 | 較差 | 易擴展格式化方法 |
| 記憶體 | 單函數 | 每秒創建實例 |
| 複用性 | 低 | 高(可實例化多個時鐘) |
簡單頁面用方式一即可;組件化項目推薦方式二,便於維護與擴展。