for循环中的JavaScript闭包 [英] JavaScript closures in for-loop
本文介绍了for循环中的JavaScript闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
for(x = 1; x < = 5; x ++){
for(y = 1; y <= 5; y ++){
var cords = x +x+ y;
var el = document.getElementById(cords);
el.addEventListener(click,function(e){B_modeWindow('1',cords);});
$ p
$ b $ p $据我所知道的信息(博客链接上面提供)无法弄清楚如何修改显示代码来解决它。
如何绕过这段代码,循环?
编辑:我不知道。易读词的定义很好。测试:对于(x = 1; x <= 5; x ++){
,
(y = 1; y <= 5; y ++){
var cords = x +x+ y;
alert(cords);
$ b $ / code $ / pre
解决方案用任何你需要关闭的参数来调用函数。在这种情况下,这是 cords
。
for(x = 1; (y = 1; y< = 5; y ++){
var cords = x +x+ y; x ++ =
var el = document.getElementById(cords);
(函数(cords){
el.addEventListener(click,function(e){B_modeWindow('1',cords);});
})(帘线);
}
}
As explained here http://www.mennovanslooten.nl/blog/post/62/ code below outputs result just for "5x5" forgetting about anything before that.
for (x = 1; x <= 5; x++) {
for (y = 1; y <= 5; y++) {
var cords = x+"x"+y;
var el = document.getElementById(cords);
el.addEventListener("click", function (e) { B_modeWindow('1', cords); });
}
}
As far I have the informations (blog link provided above) can't figure out how to alter showed code to fix it.
How to walk around this code with JavaScript closure in my for-loop?
edit: I dont get it. varibles are defined in good way. Test:
for (x = 1; x <= 5; x++) {
for (y = 1; y <= 5; y++) {
var cords = x+"x"+y;
alert(cords);
}
}
解决方案 Call the function with anything you need to be closed as an argument. In this case, that's cords
.
for (x = 1; x <= 5; x++) {
for (y = 1; y <= 5; y++) {
var cords = x + "x" + y;
var el = document.getElementById(cords);
(function(cords) {
el.addEventListener("click", function (e) { B_modeWindow('1', cords); });
})(cords);
}
}
这篇关于for循环中的JavaScript闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文