<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>简易网页时钟</title>
<style type="text/css">
body,p {margin: 0;padding: 0;}
body {color: #fff;font: 16px/1.5}
#clock {width: 300px;text-align: center;background: #1a1a1a;margin: 10px auto;padding: 20px 0;}
span {color: #000;width: 80px;line-height: 2;background: #fbfbfb;border: 2px solid #b4b4b4;margin: 0 10px;padding: 0 10px;}
</style>
<script type="text/javascript">
window.onload = function() {
var oClock = document.getElementById("clock");
var aSpan = oClock.getElementsByTagName("span");
setInterval(getTimes,1000);
getTimes();
function getTimes() {
var oDate = new Date();
var aDate = [oDate.getHours(),oDate.getMinutes(),oDate.getSeconds()];
for(var i in aDate) aSpan[i].innerHTML = format(aDate[i])
}
function format(a) {
return a.toString().replace(/^(\d)$/,"0")
}
}
</script>
<body>
<p id="clock">
<span></span>点<span></span>分<span></span>秒
</p>
</body>
</html>
1.return a.toString().replace(/^(\d)$/,"0")这句表达的是什么意思呢?
2.setInterval(getTimes(),1000)这样写不行吗?为什么?
1,
/^(d)$/
are used to match a string with only one number, such as2
,3
, etc. The function of the brackets is to store the number asgroup 1
,replace( /^(d)$/,"0$1")
is used to add0
before the number,$1
represents the string stored ingroup 1
,such as
2
is replaced by02
,3
Replace with03
,You can enter
'2'.replace(/^(d)$/,"0$1")
in theconsole
and run to see the result2. No, the first parameter of
setInterval
must be a function, andgetTimes()
is the value after running the function. OnlygetTimes
is a functionI answered two similar questions to the questioner in succession. I suggest that the questioner read the book carefully first and lay a solid foundation