循环中的对象创建中断;展开的作品 [英] Object creation in loop broken; unrolled works
本文介绍了循环中的对象创建中断;展开的作品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在做一些测试并遇到了这种奇怪的情况:第一种情况(在循环中分配 InfoWindows 之类的对象)没有按预期工作,而逐个编写分配工作.
I'm doing some testing and ran into this bizarre situation: The first case (assigning objects like InfoWindows in a loop) does not work as expected, while writing the assignments one by one does work.
预期行为是当鼠标悬停在标记上时打开 InfoWindow.许多窗户应该同时保持打开状态.
The expected behavior is for an InfoWindow to open when the mouse is over a marker. Many windows should stay open at the same time.
从表面上看,我看不出任何区别.这是怎么回事?我展示了每个案例的相关代码和完整的 JSFiddle.
Superficially, I don't see any difference. What's going on? I'm showing relevant code and a full JSFiddle for each case.
不起作用 JSFiddle
iwArray = [];
for (var i = 0; i < 3; i++) {
iwArray[i] = new google.maps.InfoWindow({content: "w "});
google.maps.event.addListener(marker[i], 'mouseover', function(e) {
iwArray[i].open(map, this);
});
}
有效,但很丑 JSFiddle
iwArray = [];
iwArray[0] = new google.maps.InfoWindow({content: "w 0"});
google.maps.event.addListener(marker[0], 'mouseover', function(e) {
iwArray[0].open(map, this);
});
iwArray[1] = new google.maps.InfoWindow({content: "w 1"});
google.maps.event.addListener(marker[1], 'mouseover', function(e) {
iwArray[1].open(map, marker[1]);
});
iwArray[2] = new google.maps.InfoWindow({content: "w 2"});
google.maps.event.addListener(marker[2], 'mouseover', function(e) {
iwArray[2].open(map, marker[2]);
});
推荐答案
使用闭包:
for (var i = 0; i < 3; i++) {
(function(i){
iwArray[i] = new google.maps.InfoWindow({content: "w "});
google.maps.event.addListener(marker[i], 'mouseover', function(e) {
iwArray[i].open(map, this);
});
})(i);
}
这篇关于循环中的对象创建中断;展开的作品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文