如何将参数传递给setTimeout调用中定义的匿名函数? [英] How to pass parameter to an anonymous function defined in the setTimeout call?
问题描述
这是我的代码:
function addRcd2(timeOut){
for(var c=0; c less 5; c++){
var rcdi = "rcd_"+c+"";
setTimeout(function(){
$('.tbl1 tbody').append(rcdi);
},timeOut*c);
}
}
此代码的输出是一个表,其中行具有相同的文本rcd_5
.
The output of this code is a table which rows have the same text rcd_5
.
我的目标是使表行具有不同的记录rcd_1
,…,rcd_5
.
My goal is to have a table rows have different records rcd_1
, …, rcd_5
.
有什么想法吗?
推荐答案
典型的循环创建函数问题.您传递给setTimeout
的所有闭包都引用了相同 rcdi
变量.在循环内定义变量与在循环内定义变量相同:
Typical creating a function in a loop problem. All closures you pass to setTimeout
have a reference to the same rcdi
variable. Defining the variable inside the loop is the same as defining it outside:
var rcdi;
for(var c=0; c < 5; c++){
rcdi = "rcd_"+c+"";
// ...
}
这使您在这里只处理一个变量更加明显.
which makes it a bit more apparent that you only deal with one variable here.
您必须引入一个新的作用域,这在JavaScript中只能通过函数来实现:
You have to introduce a new scope, which in JavaScript can only be achieved through functions:
function getCallback(val) {
return function(){
$('.tbl1 tbody').append(val);
};
}
function addRcd2(timeOut){
for(var c=0; c < 5; c++){
setTimeout(getCallback("rcd_"+c),timeOut*c);
}
}
如您在其他答案中所见,您还可以使用立即功能.使用您认为更具可读性的内容.
As you can see in other answers, you can also use immediate functions. Use what you find more readable.
这篇关于如何将参数传递给setTimeout调用中定义的匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!