问答详情
源自:7-3 返回/设置年份方法

实时钟表在body里加载不了,非要点击按钮才能实现

本来想在<body onload="simpleWatch()">实现网页加载时显示实时钟表,但是显示不了,非的用按钮点击?

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>一个简单的钟表</title>

<script type="text/javascript">

function simpleWatch(){

var date=new Date();

var year=date.getFullYear();

var month=date.getMonth();

month=addZero(month);

var day=date.getDate();

day=addZero(day);

var hour=date.getHours();

hour=addZero(hour);

var minute=date.getMinutes();

minute=addZero(minute);

var second=date.getSeconds();

second=addZero(second);

document.getElementById("p1").innerHTML=

year+"年"+month+"月"+day+"日"+hour+":"+minute+":"+second;

setTimeout("simpleWatch()",1000);

}

function addZero(x){

if(x<10){

x="0"+x;

}

return x;

}

</script>

</head>

<body>

<div id="p1"></div>

<input type="button" value="点击" onclick="simpleWatch()"/>

</body>

</html>


提问者:给大佬递茶 2018-11-13 20:50

个回答

  • 慕盖茨2396121
    2018-11-14 11:16:05
    已采纳

     var s = setInterval(function () {

             var date = new Date();

         document.getElementById("p1").innerHTML = date;

         },1000);

    //这样就是实时了