如何使数字时钟动态化?

时间:2012-01-24 15:31:53

标签: javascript

这是我的月份日历的完整代码。它还显示今天的时间。 gettime函数返回当前时间,但时间是静态的。为了让时间充满活力,我该怎么做?

<html>
<head>
<script type="text/javascript">
function gettime()
 {
  var time=new Date()
  var hour=time.getHours()
  var minute=time.getMinutes()
  var text=hour+':'+ minute
  return text
  }
function nameofmonth(month)
 {
   var monthname=new Array("January","February","March","April","May","June","July","August","September","October","November","December")
   return monthname[month]
   }
 function monthdays(month,year)
  {
    var daysofmonth=new Array(31,28,31,31,30,31,31,31,30,31,30,31)
     if(year%4==0)
       daysofmonth[1]=29  
         return daysofmonth[month]   
     }

 function table()
   {
     var now=new Date()
     var hour=now.getHours()
     var minute=now.getMinutes()
     var second=now.getSeconds()

     var date=now.getDate()
     var month=now.getMonth() 
     var year=now.getFullYear()
     now.setFullYear(year,month,1)
     var firstday=now.getDay()
     var monthname=nameofmonth(month)
     var daysofmonth=monthdays(month,year)
     if(firstday>0)
          var k=-(firstday-1)
     else
           k=1
      var table="<table border=5 cellspacing=9 cellpadding=13>"
      table +="<th colspan=7>"+monthname+" "+date+"th</th>"
      table +="<tr><th>sun</th><th>mon</th><th>tue</><th>wed</th><th>thu</th<th>fri</th><th>sat</th></tr>"
     for(var i=0;i<5;i++)
        {
          table+="<tr>"
          for(var j=0;j<7;j++)
           {
             if(k<=daysofmonth && k>0)
               { if(k==date)
                  table+='<td bgcolor="aqua">'+k+'<br>'+gettime()+ '</td>'
                  else
                   table+='<td>'+k+'</td>'
               k=parseInt(k)

             } 
            else
               table+="<td></td>"
             k++
        }
      table+="</tr>"
      }
     table+="</table>"
    document.write(table)
      }      
</script>
</head>
<body onload="table()">
</body >
</html>

2 个答案:

答案 0 :(得分:0)

<div id='clock'></div>添加到文档中。在table()中用

替换document.write
 document.getElementById("clock").innerHTML = table

写一个单独的onload函数,在此函数中使用setInterval定期调用table()

答案 1 :(得分:0)

如果我理解了你的问题,那么你需要这个。首先改变你的

table+='<td bgcolor="aqua">'+k+'<br>'+gettime()+ '</td>' 

行到

    table+='<td id="myclock" bgcolor="aqua">'+k+'<br>'+gettime()+ '</td>'

并添加另一个功能

function refreshtime()
{
     var timeis=gettime();
     document.getElementById('myclock').innerHTML=timeis;
}

然后将<body onload="table()">更改为

<body onload='table();setInterval(refreshtime,500);'>

希望这是你想要的。这将只更新您的时间。