gpt4 book ai didi

javascript - 页面上运行的时间和日期

转载 作者:行者123 更新时间:2023-12-01 00:43:52 25 4
gpt4 key购买 nike

onload 事件有问题,它没有在页面上启动 Javascript。

我尝试使用以下代码:onload="startTime()"document.getElementById("clockdate").onload = function() {startTime()};

function startTime() {
var today = new Date();
var hr = today.getHours();
var min = today.getMinutes();
var sec = today.getSeconds();
ap = (hr < 12) ? "<span>AM</span>" : "<span>PM</span>";
hr = (hr == 0) ? 12 : hr;
hr = (hr > 12) ? hr - 12 : hr;
//Add a zero in front of numbers<10
hr = checkTime(hr);
min = checkTime(min);
sec = checkTime(sec);
document.getElementById("clock").innerHTML = hr + ":" + min + ":" + sec + " " + ap;

var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var curWeekDay = days[today.getDay()];
var curDay = today.getDate();
var curMonth = months[today.getMonth()];
var curYear = today.getFullYear();
var date = curWeekDay + ", " + curMonth + " " + curDay + " " + curYear;
document.getElementById("date").innerHTML = date;

var time = setTimeout(function() {
startTime()
}, 500);
}

function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
<div id="clockdate" onload="startTime()">
<div id="clock"></div>
<div id="date"></div>
</div>

尝试显示当前时间和日期。

最佳答案

onload不适用于 div。尝试一下

document.body.onload = startTime;

较短版本

function startTime() {
var today = new Date();

document.getElementById('date').innerHTML = today.toLocaleDateString('en-US', {
weekday: 'short',
year: 'numeric',
month: 'long',
day: 'numeric'
});

document.getElementById('clock').innerHTML = today.toLocaleTimeString('en-US')

var time = setTimeout(startTime, 1000);
}

document.body.onload = startTime;
<div id="clockdate">
<div id="clock"></div>
<div id="date"></div>
</div>

关于javascript - 页面上运行的时间和日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57532902/

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