简体   繁体   English

如何将参数传递给setTimeout调用中定义的匿名函数?

[英]How to pass parameter to an anonymous function defined in the setTimeout call?

Here is my code: 这是我的代码:

function addRcd2(timeOut){  
  for(var c=0; c less 5; c++){
    var rcdi = "rcd_"+c+"";
    setTimeout(function(){
      $('.tbl1 tbody').append(rcdi);
    },timeOut*c);
  }
}

The output of this code is a table which rows have the same text rcd_5 . 此代码的输出是一个表,其行具有相同的文本rcd_5

My goal is to have a table rows have different records rcd_1 , …, rcd_5 . 我的目标是让表行具有不同的记录rcd_1 ,..., rcd_5

Any ideas? 有任何想法吗?

Typical creating a function in a loop problem. 典型地在循环问题中创建函数 All closures you pass to setTimeout have a reference to the same rcdi variable. 传递给setTimeout所有闭包都引用了相同的 rcdi变量。 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. 这使得你在这里只处理一个变量更加明显。

You have to introduce a new scope, which in JavaScript can only be achieved through functions: 您必须引入一个新的范围,在JavaScript中只能通过函数实现:

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. 使用您觉得更具可读性的内容。

function addRcd2(timeOut){  
  for(var c=0; c less 5; c++){
    var rcdi = "rcd_"+c+"";
    setTimeout((function(x) {
      return function(){
        $('.tbl1 tbody').append(x);
      };
    })(rcdi),timeOut*c);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 js:无法将参数传递给setTimeOut中的匿名函数 - js: unable to pass parameter to anonymous function in setTimeOut 如何从setTimeout调用匿名函数 - How to call an anonymous function from setTimeout 在setTimeout()中将参数传递给匿名函数 - Passing parameter to anonymous function in setTimeout() 如何在匿名函数中对同一函数进行setTimeout调用? - How to make a setTimeout call to same function from within an anonymous function? JavaScript:如何将匿名函数作为函数参数传递? - JavaScript: How to pass an anonymous function as a function parameter? 在setTimeOut函数中传递多个参数会引发Uncaught ReferenceError:方法未定义(匿名函数)? - Multiple Parameter passing in setTimeOut function throws Uncaught ReferenceError: method is not defined (anonymous function)? 如何将参数传递给自执行的匿名函数 - How to pass a parameter to a self executing anonymous function 为什么不能将函数调用(而不是函数引用或匿名函数)传递给setTimeout()? - Why can I not pass a function call (rather than a function reference or an anonymous function) to setTimeout()? 为什么settimeout()匿名函数未在javascript中调用该函数? - why settimeout() anonymous function not call the function in javascript? 将参数传递给设置 setTimeout 的函数? - Pass a parameter into a function setting a setTimeout?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM