以下脚本(由 Adam Khoury 提供)创建一个计时器,在完成时给出一条消息。该功能对我来说很有意义,但我很难理解这里字符串的使用。特别是:
1) 为什么必须将 'countDown('+secs+',"'+elem+'")'
作为字符串传递?在我见过的其他示例中,setTimeout 可以接受一个函数(不带“引号”)。
2) 同样,在同一行中,为什么必须将 elem
作为字符串传递(使用“引号”)?看起来elem
变量已经保存了一个字符串值,即id的名称(“status”
)
如果您对此有任何见解或需要纠正的误解,我将不胜感激!
<script type="text/javascript">
function countDown(secs,elem) {
var element = document.getElementById(elem);
element.innerHTML = "Please wait for "+secs+" seconds";
if(secs < 1) {
clearTimeout(timer);
element.innerHTML = '<h2>Countdown Complete!</h2>';
}
secs--;
var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
}
</script>
<div id="status"></div>
<script type="text/javascript">countDown(10,"status");</script>
最佳答案
Why must
'countDown('+secs+',"'+elem+'")'
be passed as a string?
它不必这样传递。虽然setTimeout
接受字符串,您应该避免传递字符串。当您以某种方式尝试使用对象调用回调函数时,您很快就会看到它的局限性。传递函数是一种更好的方法。
Likewise, in that same line, why must elem be passed as a string (using "quotes")? It seems that the elem variable already holds a string value, the name of the id ("status")
没错,elem
已经是一个字符串,但如果省略引号,您将创建一个字符串,例如
'countDown(10, status)'
如果setTimeout
稍后评估该字符串时,它将尝试访问变量 status
,它不存在。这就是为什么你希望最终的字符串看起来像
'countDown(10, "status")'
为此,您必须添加引号。
<小时/>因此,更简洁的实现是
var timer = setTimeout(function() {
countDown(secs, elem);
}, 1000);
请注意,该代码实际上无法正常工作。 timer
变量的作用域错误,没有任何效果并且 setTimeout
即使 secs < 1
仍会被调用.
大概应该是这样的:
function countDown(secs,elem) {
var element = document.getElementById(elem);
if(secs < 1) {
element.innerHTML = '<h2>Countdown Complete!</h2>';
return;
}
else {
element.innerHTML = "Please wait for "+secs+" seconds";
}
setTimeout(function() {
countDown(secs - 1, elem);
}, 1000);
}
关于javascript - 将函数作为参数传递时使用字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18755931/