[英]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.