javascript - <script> 在打开页面时并不总是加载

标签 javascript html css

所以我有一个基本上一致地刷新时间的脚本,以便用户看到时间与秒/分钟/小时等相加。

出于某种原因,有时当我加载页面时它可以工作,但大多数时候没有。这很不寻常,我想知道是否有人愿意提供意见。

出于样式目的,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>

最佳答案

包装你的 setIntervalwindow.onload .

...

window.onload=function(){
    setInterval(getCurrentDate,1000);
};

此外,要解决您稍后可能遇到的一些 html 问题,请移动您的 <h1>来自 <head><body> .

关于javascript - &lt;script&gt; 在打开页面时并不总是加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40557251/

相关文章:

html - anchor 标签不起作用并保持选中状态,直到我再次单击

CSS多列避免中断

javascript - 闭包中的箭头函数

javascript - jQuery AJAX 到 Node 服务器抛出 net::ERR_CONNECTION_REFUSED

Javascript for循环重复函数问题

javascript - 如何将菜单和菜单项角色的默认 JAWS 读取更改为自定义角色?

html - 我怎样才能简单地在页面右上角放置一个按钮?

javascript - 查找图像 ID 并替换为单击的按钮类

css - 如何添加wpf图像按钮?

javascript - qTip2 渲染位置错误