This article describes the dynamic time display method that implements JavaScript synchronized to local time. Share it for your reference. The specific analysis is as follows:
The example of dynamic display time is very simple. After understanding JavaScript, it is possible to complete things with a few lines of code.
But for some people who have never been exposed to JavaScript, they almost look like a big project, and then search for code online, and then cannot find it in the vast html code, and ultimately cannot get the key points.
1. Basic Objectives
Implement a web page text time that is accompanied by the client (on the browser machine) time, using the shortest code.
2. Production process
Copy the code as follows:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>jsclock</title>
</head>
<body>
<script type="text/javascript">
function clock() {
var time = new Date().toLocaleString();
document.getElementById("clock").innerHTML = time;
}
setInterval("clock()", 1000);
</script>
<span id="clock"></span>
</body>
</html>
1. If the Date object uses a constructor without parameters, it will return the client's time. The toLocaleString() method converts time to display the format of time. If it is just the toString() method, it will only convert time into a time string written in English. At the same time, I personally realized that the toLocaleTimeString() method does not exist, please do not toss. If you are not satisfied with the time of the conversion of the system's own methods, please use various methods such as getDay(), getMonth(), getFullYear() to construct the string. No display again.
2. innerHTML is equivalent to id clock all elements under clock. document.getElementById("clock").innerHTML = time; The meaning of the sentence "<span id="clock"></span>" is changed into the content of the time string.
3. The key to this JavaScript is the setInterval("clock()", 1000); function, which means that the clock() function is executed once every 1000 milliseconds, that is, every 1 second. That is, every second, the content of the <span id="clock"></span> is updated to the time string.
I hope this article will be helpful to everyone's JavaScript programming.