<html>
<head>
<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
h=checkTime(h);
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}

function checkTime(i)
{
if (i<10)
  {
  i="0" + i;
  }
return i;
}
</script>
</head>

<body onload="startTime()">
<div id="txt"></div>
</body>
</html>


我只是不太了解这两行:

document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);


有人可以用语言解释吗? getElementById('txt'),innerHTML和setTimeout('startTime()',500)有什么作用?

最佳答案

请参见documentation


getElementById获取具有给定ID的HTML DOM element
DOM元素的innerHTML属性指定元素的HTML
setTimeout方法在指定的毫秒数后运行一个函数
请注意,此代码是极差的做法。永远不要将字符串传递给setTimeout
它应该是setTimeout(startTime, 500),并传递函数本身。
您甚至可以传递匿名函数:

setTimeout(function() { alert('Five seconds later...'); }, 5000);

10-05 20:54
查看更多