我正在进行一些测试并遇到了这种奇怪的情况:第一种情况(在循环中分配像InfoWindows这样的对象)无法按预期工作,而逐个编写分配确实有效。
当鼠标悬停在标记上时,预期的行为是InfoWindow打开。许多窗户应该同时保持打开状态。
表面上看,我没有看到任何区别。发生了什么事?我为每个案例展示了相关代码和完整的JSFiddle。
不起作用 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]);
});
答案 0 :(得分:3)
var iwArray = [];
for (var i = 0; i < 3; i++) {
iwArray[i] = new google.maps.InfoWindow({content: "w " + i });
google.maps.event.addListener(marker[i], 'mouseover', createListener(i, map));
}
function createListener(i, map) {
return function(e) {
iwArray[i].open(map, this);
};
}
答案 1 :(得分:3)
使用闭包:
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);
}