我搜索,但无法找到这个看似简单的问题的答案,所以...Javascript功能问题
假设我有一个循环,我需要设置回调。我的回调函数如下:
function callback(var1) { // code }
现在我的循环是这样的:
for(//condition)
{
var x = something_different_each_time;
document.getElementById('foo').addEventListener('click', function() { callback(x); }, false);
}
现在看起来即使循环运行n次,匿名函数只有一次编译 - 因此每个回调调用都使用相同的参数调用(即使每次循环中的x都会变化)。
我必须在这里失踪的东西..任何帮助非常感谢! :)
类似的问题:http://stackoverflow.com/questions/1734749/ http://stackoverflow.com/questions/643542/ http://stackoverflow.com/questions/1582634/ HTTP: //stackoverflow.com/questions/1331769/ http://stackoverflow.com/questions/1552941/ http://stackoverflow.com/questions/750486/ http://stackoverflow.com/questions/ 933343/ http://stackoverflow.com/questions/1579978/ http://stackoverflow.com/question s/1413916/ – CMS 2010-05-21 07:57:40
这是一个综合清单@CMS。用“闭包”和“循环”标记这些问题会很好,所以它们都可以通过简单的搜索进行链接。 – Anurag 2010-05-21 08:01:56
完成,所有问题都被标记为“javascript”,“closures”和“loops”。这里的链接 - http://stackoverflow.com/questions/tagged/javascript+closures+loops – Anurag 2010-05-21 08:07:50