更新时间:2022-12-27 10:47:39
The content of the infowindow is added to the DOM asynchronously, so it can't be found until the InfoWindow
"domready" event fires.
从该文档):
准备就绪 |参数:无
当包含InfoWindow的内容附加到DOM时,将引发此事件.如果您正在动态构建信息窗口内容,则可能希望监视此事件.
要将事件侦听器附加到这些按钮,请运行JQuery代码以在"domready"事件侦听器中查找它们:
To attach event listeners to those buttons, run the JQuery code to look for them in a 'domready' event listener:
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(contentString);
infoWindow.open(map, this);
// wait for the infowindow's domready event
google.maps.event.addListenerOnce(infoWindow, 'domready', function() {
// find the elements with the "btn" class and add the click listener to the one with id="btnDirection"
var btn = $(".btn").filter('#btnDirection');
if (btn != null) {
for (var i = 0; i < btn.length; i++) {
btn[i].addEventListener('click', function() {
console.log("hello")
});
};
};
});
});
代码段:
var geocoder;
var map;
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infoWindow = new google.maps.InfoWindow();
var contentString = '<div id="other"></div><br></br>' +
'<button type="button" class="btn btn-success" id="btnDirection">Get direction</button> </div>' +
'<button type="button" class="btn btn-success" id="btnDiscount">Related discount</button> </div>';
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: map.getCenter(), // place.geometry.location,
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(contentString);
infoWindow.open(map, this);
// wait for the infowindow's domready event
google.maps.event.addListenerOnce(infoWindow, 'domready', function() {
// find the elements with the "btn" class and add the click listener to the one with id="btnDirection"
var btn = $(".btn").filter('#btnDirection');
if (btn != null) {
for (var i = 0; i < btn.length; i++) {
btn[i].addEventListener('click', function() {
document.getElementById("other").innerHTML = "Get Direction was CLICKED";
console.log("hello")
});
};
};
});
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>