gpt4 book ai didi

javascript - 刷新javascript中的时间

转载 作者:行者123 更新时间:2023-11-28 13:23:48 25 4
gpt4 key购买 nike

我一直在试图弄清楚如何在我的网页中自动刷新时间(并且仅刷新时间),但我似乎无法得到它。

这就是我所拥有的。

var d = new Date();
var weekday = d.getDay();
var day = d.getDate();
var month = d.getMonth() + 1; //JS says jan = 0
var year = d.getFullYear();
var minutes = d.getMinutes();
var hours = d.getHours() + 1; //eastern time zone
var seconds = d.getSeconds();
var ms = d.getMilliseconds();

function distime(minutes, hours, month, day, year) {
if (minutes < 10) {
var lowMin = "0" + minutes.toString();
document.getElementById("timecode").innerHTML = hours.toString() + ':' + lowMin + ' ' + month.toString() + '/' + day.toString() + '/' + year.toString();
alert("here");
} else
document.getElementById("timecode").innerHTML = hours.toString() + ':' + minutes + ' ' + month.toString() + '/' + day.toString() + '/' + year.toString();
alert("here");
};

// var clockTime = distime(minutes, hours, month, day, year);

function init(minutes, hours, month, day, year) {
alert("init");
distime(minutes, hours, month, day, year);
setTimeout(distime, 10000);
};

var initTime = init(minutes, hours, month, day, year);

时间附加在 HTML 格式的 div 中,但我没有使用 PHP。

我听说我需要使用 ajax 来做到这一点,但我不确定如何实现。

我的问题再次是:如何每 10 秒刷新一次时间,以便它能够在我的网站上正确显示。

谢谢!

解决我的问题的更新代码如下所示。

var time = {};

(function () {
var clock = document.getElementById('timecode');

(function tick () {
var minutes, d = new Date();
time.weekday = d.getDay();
time.day = d.getDate();
time.month = d.getMonth() + 1; //JS says jan = 0
time.year = d.getFullYear();
time.minutes = d.getMinutes();
time.hours = d.getHours() + 1; //eastern time zone
time.seconds = d.getSeconds();
time.ms = d.getMilliseconds();

minutes = (time.minutes < 10 ? '0' + time.minutes : time.minutes);

clock.innerHTML = time.hours + ':' + minutes + ' ' + time.month + '/' + time.day + '/' + time.year;

window.setTimeout(tick, 1000);
}()); // Note the parens here, we invoke these functions right away
}()); // This one keeps clock away from the global scope

感谢所有提供帮助的人!

最佳答案

将它们移动到一个函数:

function updateTime() {
var d = new Date();
var weekday = d.getDay();
var day = d.getDate();
var month = d.getMonth() + 1; //JS says jan = 0
var year = d.getFullYear();
var minutes = d.getMinutes();
var hours = d.getHours() + 1; //eastern time zone
var seconds = d.getSeconds();
var ms = d.getMilliseconds();

distime(minutes, hours, month, day, year);
}

setInterval(updateTime, 10000);

关于javascript - 刷新javascript中的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30980139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com