[英]Error in js code
谁能告诉我为什么这个JS代码不起作用?
它应该每秒打印一次时间:
function stampajDatum(){
var now = new Date();
var sat = now.getHours();
var mins = now.getMinutes();
var sec = now.getSeconds();
document.write(sat + ":" + mins + ":" + sec);
}
setInterval("stampajDatum()", 1000);
我在控制台中收到的第一条消息是关于该隐含评估的。 在setInterval("stampajDatum()", 1000);
函数名称周围的引号setInterval("stampajDatum()", 1000);
(将其setInterval(stampajDatum(), 1000);
)
我通常不使用setInterval()
,但是我知道setTimeout()
可以工作。 这是一个例子:
function stampajDatum(){
var now = new Date();
var sat = now.getHours();
var mins = now.getMinutes();
var sec = now.getSeconds();
document.write(sat + ":" + mins + ":" + sec);
setTimeout(stampajDatum(), 1000);
}
stampajDatum();
function stampajDatum(){
var now = new Date();
var sat = now.getHours();
var mins = now.getMinutes();
var sec = now.getSeconds();
document.write(sat + ":" + mins + ":" + sec);// the problem is here
//This writes content to a place after script block
//if the script is in head then nothing is visible.
//use something like this:
//document.getElementById('timer').innerHTML = sat + ":" + mins + ":" + sec;
}
setInterval("stampajDatum()", 1000);//This is OK but setInterval(stampajDatum, 1000); is better.
//Note that there is no () after stampajDatum
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.