如何将参数传递给setTimeout函数 [英] How to pass parameters to setTimeout function
本文介绍了如何将参数传递给setTimeout函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是javascript的新手.我编写了一个简单的计数器程序,该程序从10开始递减计数,直到达到1.
I am relatively novice to javascript. I have written a simple counter program that starts count down from 10 till it reaches 1.
<script type="text/javascript">
function countDown(secs) {
var element = document.getElementById("status");
element.innerHTML = "Please wait for "+secs+" seconds";
if(secs < 1) {
clearTimeout(timer);
element.innerHTML = '<h2>Countdown Complete!</h2>';
element.innerHTML += '<a href="#">Click here now</a>';
}
secs--;
---> **var timer = setTimeout('countDown('secs')',1000);**
}
</script>
<div id="status"></div>
<script type="text/javascript">countDown(10);</script>
然后我尝试将参数作为'+ secs +'
传递给countDown函数.
Then I tried passing parameter as '+secs+'
to the countDown function.
var timer = setTimeout('countDown('+secs+')',1000);
以上更改有效.
我的问题是,为什么我需要将参数传递为"+ secs +"而不是仅传递"secs"?有什么区别?
My question is why should I need to pass parameter as '+secs+' and NOT only 'secs' ? What difference does it make?
推荐答案
使用
var timer = setTimeout(function(){
countDown(secs)
},1000);
或
var timer = setTimeout('countDown(' + secs + ')',1000);
在您的情况下,问题是您使用带有不带 +
符号的变量的字符串连接(我的第二个示例)会导致语法错误
In your case the problem was your were using string concatenation with a variable without +
sign (my second example) with will cause a syntactical error
这篇关于如何将参数传递给setTimeout函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文