有人可以告诉我为什么这个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);
答案 0 :(得分:0)
我在控制台中收到的第一条消息是关于隐含的评估。取消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();
答案 1 :(得分:0)
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