0

在 infoBubble Google 地图中,我添加了一个函数,但是第一次打开 infoBubble 时,代码不起作用,如果我打开第二个 infoBubble 或关闭第一个并重新打开,代码会起作用。请帮忙。这是我的页面

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Documento senza titolo</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.20&sensor=false"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/infobubble.js"></script>
<script>
var infoBubble = new InfoBubble();
var infowindow = new google.maps.InfoWindow(); 
var map;
function initialize() {   
var config = {
    el: 'map',
    lat: 40.2329,
    lon: -3.42,
    zoom: 10,
    type: google.maps.MapTypeId.ROADMAP
};

var data = [        
['Giorgio Rossi',  40.15, -3.42,  '1' ], 
['Marta Bianchi',  40.25, -3.42,  '2'],
['Carlo Verdi',    40.15, -3.62,  '3'],
['Mario Giallo',   40.25, -3.62,  '4'],    
];

    var map = new google.maps.Map(document.getElementById(config.el), {
        zoom: config.zoom,
        scrollwheel: false,
        center: new google.maps.LatLng(config.lat, config.lon),
        mapTypeId: config.type
    });

 var markers = [];
 var i ;
    for (i = 0; i < data.length; i++) {          
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(data[i][1], data[i][2]),              
            map: map
        });           
marker.info = '<div id="'+data[i][3]+ '">'+data[i][0]+ '</div>';           
marker.html = '<div style="padding:25px"><a class="testClass" href="javascript:;" > My Friend '+data[i][3]+'</a> </div>';

google.maps.event.addListener(marker , 'click', function(){ 
    infoBubble.setContent(this.html);
    infoBubble.open(map, this);
    var prova = this.info;
    var found = $(prova).attr('id');
    google.maps.event.addListenerOnce(infoBubble, 'domready', function ()   {           
     $(".testClass").click(function () {
     alert(found);        
    })      
}); 
});
    }

}

google.maps.event.addDomListener(window, 'load', initialize);
</script>

</head>

<body>
<div id="map" style="width:700px; height:500px"></div>
</body>
</html>
4

1 回答 1

1

正如您从这个 SO question接受的答案中看到的那样, 您的问题与代码中的错误有关infobubble.js

更具体地说,domready触发器的位置是在代码的错误部分,在异步setMap()调用之前,而不是函数中将 infobubble 元素添加到 DOMonAdd()之后(在函数之后setMap()调用)。

这意味着在您的第一次标记单击时domready,元素尚未添加到 DOM 中 - 但它们几毫秒之后 - 这就是第二次标记单击起作用的原因。


我修复了domready位置infobubble.js并创建了一个拉取请求,该请求已被接受,现在已合并到官方代码中。

如果您更新infobubble.js 到最新的提交(暂时使用非缩小版),您可能会看到您的问题已解决。

此处使用旧代码的非工作 JS Fiddle 。在这里使用新代码
工作 JS Fiddle 。

于 2015-11-05T19:17:32.990 回答