非常に高い忠実度が必要ない場合は、次の方法を使用できます。
var container = document.getElementById("updatetime").firstChild;
var values = container.nodeValue.split(":");
// Because there is only a datetime specified, I assume is the current date
var now = new Date();
var time = new Date(now.getFullYear(), now.getMonth(), now.getDate(),
values[0], values[1], values[2]).getTime();
setInterval(function() {
time += 1000;
var date = new Date(time);
var values = [date.getHours(), date.getMinutes(), date.getSeconds()];
for (var i = 0; i < 3; i++)
if (values[i] < 10)
values[i] = "0" + values[i];
container.nodeValue = values.join(":");
}, 1000);
現在のコンピュータ クロックとより同期させたい場合は、適切な経過時間で引数を使用setTimeout
および調整することをお勧めします。delay
更新: コメントによると、更新する要素は 1 つと複数だけではなく、コードは jQuery を使用しているようです。class
ここでは、それらを識別するために使用する複数の要素に対して機能するアプローチを示します。
var containers = $(".updatetime");
var times = [];
var now = new Date();
containers.each(function(index, node) {
var values = $(node).text().split(":");
times[index] = new Date(
now.getFullYear(), now.getMonth(), now.getDate(),
values[0], values[1], values[2]).getTime();
});
setInterval(function() {
containers.each(function(index, node) {
times[index] += 1000;
var date = new Date(times[index]);
var values = [date.getHours(), date.getMinutes(), date.getSeconds()];
for (var i = 0; i < 3; i++)
if (values[i] < 10)
values[i] = "0" + values[i];
$(node).text(values.join(":"));
});
}, 1000);