JavaScript basics
JavaScript display time on webpage
JavaScript can easily display the current time on the web page. You only need to write a function with new Date() and setTimeout. This article introduces two ways of expression, one is more original and simpler, but Most people can't understand it. The second is a slightly organized representation.
Example 1: JavaScript basic syntax for displaying time on a web page
<script language="JavaScript">
function ShowTime(){
document.getElementById('showbox').innerHTML = new Date();
setTimeout('ShowTime()',1000);
}
</script>
<body onload=" ShowTime()">
<div id="showbox"></div>
</body>
This way of writing is relatively simple. First, we wrote a function called ShowTime(). The first line in it means to find the area element of showbox, and then write the current time, and the time is directly used new Date() To indicate that the following line setTimeout('ShowTime()',1000); means to re-execute this function every second. <body onload="ShowTime()"> means that when the webpage is loaded, the ShowTime function is executed directly, so that the time will appear on the webpage and it will be updated every second.function ShowTime(){
document.getElementById('showbox').innerHTML = new Date();
setTimeout('ShowTime()',1000);
}
</script>
<body onload=" ShowTime()">
<div id="showbox"></div>
</body>
Example 2: Advanced grammar of JavaScript displaying time on webpage
<script language="JavaScript">
function ShowTime(){
var NowDate=new Date();
var h=NowDate.getHours();
var m=NowDate.getMinutes();
var s=NowDate.getSeconds();
document. getElementById('showbox').innerHTML = h+'hour'+m+'minute'+s+'second';
setTimeout('ShowTime()',1000);
}
</script>
<body onload="ShowTime()">
<div id="showbox"></div>
</body>
function ShowTime(){
var NowDate=new Date();
var h=NowDate.getHours();
var m=NowDate.getMinutes();
var s=NowDate.getSeconds();
document. getElementById('showbox').innerHTML = h+'hour'+m+'minute'+s+'second';
setTimeout('ShowTime()',1000);
}
</script>
<body onload="ShowTime()">
<div id="showbox"></div>
</body>
The results displayed by the advanced grammar are more suitable for human reading. We use NowDate to represent the object of now Date() and assign it to h (hour), m (minute), s (second) and then display it on the web page. Here we Using the call time techniques getHours(), getMinutes() and getSeconds(), we get the introduction of today's date in JavaScript .
Post a Comment
0 Comments