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


出于某种原因,有时当我加载页面它工作,但大多数时候没有。这是非常不寻常的,我想知道是否有人会有输入。


为了造型,em标签真的需要留在h1。
& #xA;
这是我的代码:


 < head>

< link rel =“ stylesheet“type =”text / css“href =”styling.css“>
< h1> Trade Shack< em id =”demo“>< / em>< / h1>&# XA;<标题>主页< /标题>

<脚本>
 function getCurrentDate(){
 var fullDate = new Date();
 var day = fullDate.getDay();
 var stringDays = [“Sunday”,“Monday”,“Tuesday”, “星期三”,“星期四”,“星期五”,“星期六”];
 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 +“,”+小时+“:”+分钟+“:”+秒;

}

 setInterval(getCurrentDate,1000);
< / script>&#xA ;
 < /头>
 代码>


答案 0 :(得分:1)
首先你应该删除h1元素(以及它内部的所有元素)并将其放在文档的body标签上,然后使用window.onload
事件,这就是你要称之为pice的地方代码setInterval(getCurrentDate,1000);
您可以在此处查看window.onload
的使用情况
http://www.w3schools.com/jsref/event_onload.asp
我希望它有效:)
答案 1 :(得分:1)
将setInterval
包裹在window.onload
。
...
window.onload=function(){
setInterval(getCurrentDate,1000);
};
此外,要修复以后html可能遇到的一些问题,请将<h1>
从<head>
移至<body>
。
答案 2 :(得分:1)
即使找不到“demo”,也要确保该功能正常工作。否则,它可能导致阻塞错误并阻止进一步执行。并把&lt; h1&gt;在身体而不是头部。
<head>
<link rel="stylesheet" type="text/css" href="styling.css"/>
<title>Homepage</title>
<script>
function getCurrentDate() {
var demo = document.getElementById("demo");
if (!demo) {return;}
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();
demo.innerHTML = stringDays[day] + ", " + stringMonth[month] + " " + numDay + ", " + year + ", " + hour + ":" + minute + ":" + second;
}
setInterval(getCurrentDate, 1000);
</script>
</head>
<body>
<h1>The Trade Shack<em id="demo"></em></h1>
<!--More HTML here-->
</body>