0

我正在使用 Bing Maps 来实现在地图上放置多个图钉。每当按下图钉时,我都会弹出一个信息框,并且在信息框中我有一个编辑按钮。当按下编辑按钮时,我希望它显示与引脚相关的标题(测试目的)。但是,每当我在 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);
        }
4

2 回答 2

1
pinInfobox.setOptions({
    actions: [{
        label: "Edit",
        eventHandler: (function (infoBox) {
            return (function (mouseEvent) {
                alert(infoBox.getTitle());
            })
        })(pinInfobox)
    }]
});
于 2013-05-28T18:06:33.030 回答
1

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

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]在每次调用它时都会对您的特定引用。这使您不会遇到循环问题。

于 2013-05-28T17:47:51.080 回答