for循环中的匿名函数

时间:2013-05-28 17:44:07

标签: javascript

我正在使用Bing Maps实现在地图上放置多个图钉。每当按下一个引脚我都有一个信息框弹出窗口,在信息框中我有一个编辑按钮。当按下编辑按钮时,我希望它显示与引脚相关的标题(测试目的)。但是,每当我在for循环中为每个引脚添加一个处理程序时,只使用最后一个处理程序......例如,如果我添加三个带有标题的引脚:[hello,foo,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);
        }

2 个答案:

答案 0 :(得分: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]进行特定引用。这样可以避免出现循环问题。

答案 1 :(得分:1)

pinInfobox.setOptions({
    actions: [{
        label: "Edit",
        eventHandler: (function (infoBox) {
            return (function (mouseEvent) {
                alert(infoBox.getTitle());
            })
        })(pinInfobox)
    }]
});