日期:2014-05-16  浏览次数:20414 次

js时钟无法实现,求解答
<body>
<script type="text/javascript">
function the_time()
{
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();

minutes = fixTime(minutes);
seconds = fixTime(seconds);

var time_string = hours + ":" + minutes + ":" + seconds;

document.write(time_string);
setTimeout("the_time();",100);
}

function fixTime(number)
{
if(number < 10)
number = "0" + number;
return number;
}
</script>
</body>

------解决方案--------------------
<div id="time"></div>
<script type="text/javascript">
function show_time(){
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth() + 1;
var day = today.getDate();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
if(month<10){
month='0'+month;
}
if(day<10){
day='0'+day;
}
if(h<10){
h='0'+h;
}
if(m<10){
m='0'+m;
}
if(s<10){
s='0'+s;
}
var now = year + "-" + month + "-" + day + " " + h + ":" + m + ":" + s

document.getElementById("time").innerHTML = now;
}

window.setInterval('show_time();', 1000);
</script>
看看这个吧
------解决方案--------------------
JScript code

<html>
<body>

<input type="text" id="time" size="35" />
<script language=javascript>
var int=self.setInterval("the_time()",50)
function the_time()
  {

var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
minutes = fixTime(minutes);
seconds = fixTime(seconds);
var time_string = hours + ":" + minutes + ":" + seconds;
  document.getElementById("time").value=time_string;
  }
function fixTime(number)
{
if(number < 10)
number = "0" + number;
return number;
}
</script>
<button onclick="int=window.clearInterval(int)">Stop interval</button>

</body>
</html>

------解决方案--------------------
问题出在你the_time()方法没有绑定在页面dom元素的事件上面,是不会被调用的
------解决方案--------------------
1、setTimeout("the_time();",100); 调用有问题,你写在了 the_time()里面。而 the_time() 函数没调用,因此里面永远不会执行。
2、 document.write + setTimeout 会卡死页面 

解决方法如 #1