Move javascript clock code from html file to an external .js file
So I have made a clock, it works great. Now I want to move the javascript into an external file and link to it with
<SCRIPT type="text/javascript" language="JavaScript" src="clock.js"
</SCRIPT>
I can not figure out how to keep it updating though. I have tried a few things and the results where: time is static at when the page loads, the prints across the screen for every update, and no time at all.
<html>
<head>
<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10开发者_StackOverflow社区)
{
i="0" + i;
}
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
Here's how I would do it. Put this code in your external js file:
function startTime() {
var today=new Date(),
h=today.getHours(),
m=today.getMinutes(),
s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
}
function checkTime(i) {
if (i<10) {
i="0" + i;
}
return i;
}
And then in your main html page, something like this:
<body onload="setInterval(startTime, 500);">
You're missing ending >
<
SCRIPT type="text/javascript" language="JavaScript" src="clock.js">
so it should be
<SCRIPT type="text/javascript" language="JavaScript" src="clock.js">
</SCRIPT>
精彩评论