字符串变量实例的问题

problem with instance of string var

本文关键字:问题 实例 变量 字符串      更新时间:2023-09-26

我正在做一个循环,在每次迭代中,我都会设置一个名为content的字符串var,这个var我用来创建一些谷歌地图标记的infoWindows。但是,在每次更改var值而不是创建新实例的迭代中,这会修改值,并始终将标记的infoWindows设置为var的最后一个值content,这就是为什么我做错了。

    for (var i = 0; i < info.length; i++) {
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(info[i].split(',')[5],
                                        info[i].split(',')[6]),
            optimized: false,
            map: map,
            zoom: 6,
            draggable: true,
            animation: google.maps.Animation.DROP
        });

        var content = '<p>Central: ' + info[i].split(',')[1] + '</p>';
        var infoWindow = new google.maps.InfoWindow({
            content:  content
        });
        google.maps.event.addListener(marker, 'click', function () {
            infoWindow.open(map, this);
            currentMarker = this;
        });
    }
google.maps.event.addListener(marker, 'click', function () {
    infoWindow.open(map, this);
    currentMarker = this;
});

正在创建一个闭包,并且infoWindow指向外部函数变量,所以所有处理程序都打开相同的infoWindow。javascript中只有函数作用域(没有一个for、if等(。使用闭包来实现您想要的:

google.maps.event.addListener(marker, 'click', (function(infoW){
    return function () {
        infoW.open(map, this);
        currentMarker = this;
    };
})(infoWindow));

这确实很奇怪。

您是否尝试使内容构建内联?

var infoWindow = new google.maps.InfoWindow({
    content:  '<p>Central: ' + info[i].split(',')[1] + '</p>'
});