Javascript:闭循环? [英] Javascript: closure of loop?
本文介绍了Javascript:闭循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想做以下事情:
for(var i = 0; i < ++ i){
/ pre>
createButton(x,y,function(){alert(button+ i +pressed);}
}
这是因为我总是得到
i
的最终值,因为Javasript的闭包不是by-值。
那么我该如何使用javascript呢?解决方案
for(var i = 0; i <10; i ++){
(function(i){
createButton(function(){alert(button+ i +pressed); });
})(i);
}
不喜欢这种模式,它抛出不要在一个循环内使函数。
在线演示 http://jsfiddle.net/simevidas/ZKeXX/ =nofollow> http://jsfiddle.net/simevidas/ZKeXX/
I would like to do the something along the following:
for(var i = 0; i < 10; ++i) { createButton(x, y, function() { alert("button " + i + " pressed"); } }
The with this is that I always get the final value of
i
because Javasript's closure is not by-value.
So how can I do this with javascript?解决方案for(var i = 0; i < 10; i++) { (function(i) { createButton(function() { alert("button " + i + " pressed"); }); })(i); }
Note that JSLint doesn't like this pattern. It throws "Don't make functions within a loop.".
Live demo: http://jsfiddle.net/simevidas/ZKeXX/
这篇关于Javascript:闭循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文