匿名函数

时间:2015-11-20 21:42:22

标签: javascript google-maps anonymous-function

我正在尝试在Google地图中创建交互式标记。这是创建标记的数组:

var markers = [
    {"id":17,"ti":"33 Star Hotel","lat":3.14648,"lng":101.711,"ty":5,"lid":"3","desc":""},
    {"id":9,"ti":"Aquaria KLCC","lat":3.15392,"lng":101.713,"ty":10,"lid":"3","desc":""},
    {"id":28,"ti":"Batu Ferringhi","lat":5.47436,"lng":100.247,"ty":15,"lid":"4","desc":""},
];

如果标记位置id lid 等于n,则标记将添加到地图 n

单击标记时,我希望显示标记数组索引,但它们都显示 i (markers.length)的最终值。

function map_center(n) {
    for ( var i = 0; i < markers.length; i++ ) {
        if ( markers[i].lid == n ) {
            var m = new google.maps.Marker({
                position: { lat: markers[i].lat, lng: markers[i].lng },
                map: map,
                title: markers[i].ti,
                icon: icons[markers[i].ty],
            });
            m.addListener( "click", function(){
                alert("click:" + i );
            });
            markers[i].dom = m;
        }
    }
}

不知何故,匿名函数需要一个参数来获取 i 的当前值的副本。我在SO上找到了这个解决方案并且它可以工作,但我不喜欢以这种方式传递参数:

var m = new google.maps.Marker({
    position: { lat: markers[i].lat, lng: markers[i].lng },
    map: map,
    title: markers[i].ti,
    icon: icons[markers[i].ty],
    i: i
});
m.addListener( "click", function(){
    alert("click:" + this.i );
});

如何妥善完成?

1 个答案:

答案 0 :(得分:1)

将所有东西包裹在生命中

function map_center(n) {
for ( var i = 0; i < markers.length; i++ ) {
    (function(i) {
        if ( markers[i].lid == n ) {
            var m = new google.maps.Marker({
                position: { lat: markers[i].lat, lng: markers[i].lng },
                map: map,
                title: markers[i].ti,
                icon: icons[markers[i].ty],
            });
            m.addListener( "click", function(){
                alert("click:" + i );
            });
            markers[i].dom = m;
        }
    })(i)
}