在按钮上添加事件监听器 - Javascript

时间:2017-02-17 17:51:30

标签: javascript google-maps event-listener

我正在尝试在按钮上添加一个动态添加到谷歌地图信息窗口的事件监听器。

  var contentString = '<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: place.geometry.location,
         icon: './Google_Maps_Markers/darkgreen_MarkerK.png'
  });

  google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(contentString);
        infoWindow.open(map, this);

        var btn = $(contentString).filter('#btnDirection'); 
        if(btn != null){
             for(var i=0; i<btn.length; i++){
                  btn[i].addEventListener('click', function()           
                       { console.log("hello") });
             };
         };   
 });

按钮显示在每个信息窗口上,但是当我点击任何信息时都会显示。

有人可以帮我这个吗?

4 个答案:

答案 0 :(得分:2)

infowindow的内容以异步方式添加到DOM中,因此在InfoWindow“domready”事件触发之前无法找到它。

来自that documentation):

  

domready |参数:无   当包含InfoWindow的内容附加到DOM时会触发此事件。 如果要动态构建信息窗口内容,您可能希望监控此事件。

要将事件侦听器附加到这些按钮,请运行JQuery代码以在“domready”事件侦听器中查找它们:

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")
        });
      };
    };
  });
});

proof of concept fiddle

代码段

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>

答案 1 :(得分:0)

一种解决方案是:

google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(contentString);
        infoWindow.open(map, this);

        $('#btnDirection').bind('click', function() {          
            console.log("hello direction") 
        }); 

        $('#btnDiscount').bind('click', function() {          
            console.log("hello discount") 
        }); 
 });

完整代码:

 var contentString = '<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,
         icon: './Google_Maps_Markers/darkgreen_MarkerK.png'
  });

  var map;
  $(document).ready(function(){
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 8
        });
		var marker = new google.maps.Marker({
				 map: map,
				 animation: google.maps.Animation.DROP,
				 position: {lat: -34.397, lng: 150.644}
		  });
		  
		  var infoWindow = new google.maps.InfoWindow();
		  
		google.maps.event.addListener(marker, 'click', function() {
			infoWindow.setContent(contentString);
			infoWindow.open(map, this);

			$('#btnDirection').bind('click', function() {          
				alert("hello direction") 
			}); 

			$('#btnDiscount').bind('click', function() {          
				alert("hello discount") 
			}); 
		});
     }
	 
	 initMap();
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
</head>
<body>
	<div id="map" style="height:100vh;"></div>
</body>
</html>

答案 2 :(得分:0)

如果你将使用相同的id,那么事件将在所有具有相同id的按钮上存档,你应该为每个按钮使用不同的Id。

答案 3 :(得分:-1)

在向DOM动态添加内容时(作为infoWindow - 内容),您必须在事件绑定之前存在的父元素上注册eventListener(例如{{1 }或body - 容器)。

您可以通过执行以下操作来实现此目的:

map
  

第二个可以工作,但当我点击其中一个按钮时,它会对所有按钮执行操作,因为我正在向infowindows添加具有相同ID的按钮。你知道我怎么解决这个问题?

ID应该是唯一的!对具有相同用途/含义的元素使用类。很抱歉在这里回答这个问题,我无法在主要问题上添加评论(还没有足够的声誉)。