萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實時顯示當前時間的兩種實現方式

HTML 容器

<span id="clock" style="font-size:14px;"></span>

方式一:函數遞歸 setTimeout

$(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);
}

方式二:面向對象封裝 Clock 類

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"));
});

關鍵點對比

特性方式一方式二
代碼風格過程式面向對象
擴展性較差易擴展格式化方法
記憶體單函數每秒創建實例
複用性低高(可實例化多個時鐘)

簡單頁面用方式一即可;組件化項目推薦方式二,便於維護與擴展。

copyright © 萬盛學電腦網 all rights reserved