所以我有一个基本上一致地刷新时间的脚本,以便用户看到时间与秒/分钟/小时等相加。
出于某种原因,有时当我加载页面时它可以工作,但大多数时候没有。这很不寻常,我想知道是否有人愿意提供意见。
出于样式目的,em 标签确实需要保留在 h1 中。
这是我的代码:
<head>
<link rel="stylesheet" type="text/css" href="styling.css">
<h1>The Trade Shack<em id="demo"></em></h1>
<title>Homepage</title>
<script>
function getCurrentDate(){
var fullDate = new Date();
var day = fullDate.getDay();
var stringDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var month = fullDate.getMonth();
var stringMonth = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var numDay = fullDate.getDate();
var year = fullDate.getFullYear();
var hour = fullDate.getHours();
var minute = fullDate.getMinutes();
var second = fullDate.getSeconds();
document.getElementById("demo").innerHTML = stringDays[day] + ", " + stringMonth[month] + " " + numDay + ", " + year + ", " + hour + ":" + minute + ":" + second;
}
setInterval(getCurrentDate,1000);
</script>
</head>
最佳答案
包装你的 setInterval
在window.onload
.
...
window.onload=function(){
setInterval(getCurrentDate,1000);
};
此外,要解决您稍后可能遇到的一些 html 问题,请移动您的 <h1>
来自 <head>
至 <body>
.
关于javascript - <script> 在打开页面时并不总是加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40557251/