JavaScript中关闭 [英] Closure in Javascript
本文介绍了JavaScript中关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
将值传递到onclick
我有100个ids < c $ c> divNum0 ,..., divNum99
。每次点击时,应使用正确的参数调用 doTask
。
I have 100 elements with ids divNum0
,...,divNum99
. Each when clicked should call doTask
with the right parameter.
下面的代码不幸的是没有关闭i,因此对所有元素调用doTask
。
The code below unfortunately does not close i, and hence doTask
is called with 100 for all the elements.
function doTask(x) {alert(x);}
for (var i=0; i<100; ++i) {
document.getElementById('divNum'+i).addEventListener('click',function() {doTask(i);},false);
}
有没有可以使用正确的参数调用函数?
Is there someway I can make the function called with right parameters?
推荐答案
是重复,我想指出一个更高级的方法 - 用迭代器替换循环,它有效地解决了JavaScript后期绑定关闭问题。
Although the (correct) answer is the duplicate, I'd like to point out a more advanced method - replacing loops with iterators, which effectively solves javascript "late-bound" closures problem.
loop = function(start, end, step, body) {
for(var i = start; i != end; i += step)
body(i)
}
loop(1, 100, 1, function(i) {
// your binding stuff
})
这篇关于JavaScript中关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文