gpt4 book ai didi

javascript - for循环中的匿名函数

转载 作者:行者123 更新时间:2023-12-02 18:41:25 26 4
gpt4 key购买 nike

我正在使用 Bing map 来实现在 map 上放置多个图钉。每当按下图钉时,我都会弹出一个信息框,并且在信息框中有一个编辑按钮。当按下编辑按钮时,我希望它显示与引脚关联的标题(测试目的)。但是,每当我在 for 循环中为每个引脚添加处理程序时,仅使用最后一个处理程序...例如,如果我添加三个标题为 [hello, foo, bar] 的引脚,则无论我使用哪个引脚,都会显示 bar单击...这是我正在做的事情:

for ( var pos = 0; pos < locationsSize; pos++) {

var locationFromIndex = locations[pos];
var bingLocation = new Microsoft.Maps.Location(
locationFromIndex.latitude, locationFromIndex.longitude);

// Create/add the pin
var pin = new Microsoft.Maps.Pushpin(bingLocation, {
width : 25,
height : 39,
anchor : mAnchor
});
pins.push(pin);

// Create/add the pin info box
var pinInfobox = new Microsoft.Maps.Infobox(pin.getLocation(), {
title : locationFromIndex.type,
visible : false,
height : 75,
zIndex : i,
width : 150,
offset : mOffset,
})
pinInfobox.setOptions({
actions : [ {
label : "Edit",
eventHandler : function(mouseEvent) {
alert(pinInfobox.getTitle()); // Only the last eventHandler added is being used...
}
} ]
});
map.entities.push(pinInfobox);
}

最佳答案

解决问题的最简单的解决方案是闭包:

for ( var pos = 0; pos < locationsSize; pos++) {
(function(locationFromIndex) {
var bingLocation = new Microsoft.Maps.Location(
locationFromIndex.latitude, locationFromIndex.longitude);

// Create/add the pin
var pin = new Microsoft.Maps.Pushpin(bingLocation, {
width : 25,
height : 39,
anchor : mAnchor
});
pins.push(pin);

// Create/add the pin info box
var pinInfobox = new Microsoft.Maps.Infobox(pin.getLocation(), {
title : locationFromIndex.type,
visible : false,
height : 75,
zIndex : i,
width : 150,
offset : mOffset,
})
pinInfobox.setOptions({
actions : [ {
label : "Edit",
eventHandler : function(mouseEvent) {
alert(inInfobox.getTitle()); // Only the last eventHandler added is being used...
}
} ]
});
map.entities.push(pinInfobox);
}
})(locations[pos]);

闭包关闭了它的包含范围,但在每次调用它时都会有一个对您的locations[pos]的特定引用。这使您不会遇到循环问题。

关于javascript - for循环中的匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16798297/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com