【发布时间】:2016-01-12 09:27:22
【问题描述】:
我想在for 循环内对setTimeout 内的templates[i] 执行点击
for(var i=0; i<templates.length; i++){
setTimeout(function(){
(function(){
templates[i].click();
}(i, templates));
}, 200);
}
我收到错误 templates[i] 未定义。
但是,这样的事情可以正常工作:
for(var i=0; i<templates.length; i++){
setTimeout(function(){
(function(){
console.log(templates_arr+templates)
}(templates_arr, templates));
}, 200);
}
谁能解释一下为什么会这样以及如何正确传递数组和索引?
谢谢, 丹
【问题讨论】:
-
这是因为在执行 IIFE 时,
i的值已更改为templates.length -
这是一个范围问题。一旦超时触发,
i将不再在范围内。 -
所以应该是
for (var i = 0; i < templates.length; i++) { (function(i, templates) { setTimeout(function() { templates[i].click(); }, 200); }(i, templates)); } -
谢谢大家。通过传递一个在那个时刻肯定是相同的值来解决。
for(var i=0; i<templates.length; i++){ setTimeout(function(){ (function(){ templates[templates_arr.length].click(); }(templates)); }, 200); setTimeout(function(){ (function(){ templates_arr.push(htmlDecode(mainwindow.document.getElementById('XmlFrame').contentDocument.getElementById('id_1').innerHTML)); }(templates_arr, templates)); }, 200); } -
@JohannesJander 你正在创建多个函数实例,你可以使用
var func = function(template) { setTimeout(function() { template.click(); }, 200); }; for (var i = 0; i < templates.length; i++) { func(templates[i]); }解决它
标签: javascript arrays for-loop settimeout self-invoking-function