以下代码片段使用函数 setInterval() 来不断更新“时钟”。唯一的区别在于函数调用 setInterval()。
当我更改 setInterval 参数时
setInterval('updateTime()',1000);
到
setInterval(updateTime(),1000);
[从单引号到无引号],它不起作用。谁能给我解释一下吗?
单引号:
<head>
<script>
function updateTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var now= h+':'+m+':'+s;
document.getElementById('timer').innerHTML = h+':'+m+':'+s;//set the text in 'timer' id below to the date
setInterval('updateTime()', 1000); //////SEE THIS LINE//////
}
</script>
</head>
<body>
<p id='timer'> Time </p>
<script>
updateTime();
</script>
</body>
没有引号:
<head>
<script>
function updateTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var now= h+':'+m+':'+s;
document.getElementById('timer').innerHTML = h+':'+m+':'+s;//set the text in 'timer' id below to the date
setInterval(updateTime(), 1000);//////SEE THIS LINE//////
}
</script>
</head>
<body>
<p id='timer'> Time </p>
<script>
updateTime();
</script>
</body>
用于测试的在线js控制台可以在这里找到:https://jsfiddle.net/
最佳答案
setInterval('updateTime()', 1000);
您将字符串作为第一个参数传递给 setInterval。您需要传递函数引用
正确的方法
setInterval(updateTime, 1000)
关于javascript - 使用单引号与不使用引号的函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38166900/