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

敢进来不? 江湖救急,急急急。在线等。
<!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>时钟的动态情况</title>
  <script type = "text/javascript">
  function clock_12h() {
  document.write("<h2>CSDN论坛欢迎您!<h2/>");
  document.write("<br/>");
  var today = new Date();
  var year = today.getFullYear();
  var month = today.getMonth() + 1;
  var date = today.getDate();
  var day = today.getDay();
  var hh = today.getHours();
  var mm = today.getMinutes();
  var ss = today.getSeconds();
  switch (day) {
  case 0:
  day = "星期日";
  break;
  case 1:
  day = "星期一";
  break;
  case 2:
  day = "星期二";
  break;
  case 3:
  day = "星期三";
  break;
  case 4:
  day = "星期四";
  break;
  case 5:
  day = "星期五";
  break;
  case 6:
  day = "星期六";
  break;
  default:
  day = "error";
  break;
  }
  document.getElementById("myclock").innerHTML = ("<h2>今天是:" + year + "年" + month + "月" + date + "日" + "&nbsp;&nbsp;" + hh + ":" + mm + ":" + ss + "&nbsp;&nbsp;" + day + "<h2/>")
  }
  var MyTimer = setInterval("clock_12h()", 1000);
  </script>
</head>
<body >
<div id = "myclock"></div>
</body>
</html>

这样写会报错,说什么行: 45
错误: 无法设置属性“innerHTML”的值: 对象为 null 或未定义,

如果把这行代码:
document.getElementById("myclock").innerHTML = ("<h2>今天是:" + year + "年" + month + "月" + date + "日" + "&nbsp;&nbsp;" + hh + ":" + mm + ":" + ss + "&nbsp;&nbsp;" + day + "<h2/>")

改成这样的话:
document.write("<h2>今天是:" + year + "年" + month + "月" + date + "日" + "&nbsp;&nbsp;" + hh + ":" + mm + ":" + ss + "&nbsp;&nbsp;" + day + "<h2/>")

就行了,但。。。问题又出现了时间不会动啊,是静止的。相当于这句代码没写。
var MyTimer = setInterval("clock_12h()", 1000); 哎。。。到底是什么回事? 找了好久没找出原因, 各位帮忙改改代码,感激不尽啊。

------解决方案--------------------
HTML是从上到下解释执行的,解释到.innerHTML那一句时div都没生成当然会出错了

另外document.write会覆盖原来的所有代码,包含script的,所以当然就不再执行了


HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://w