【问题标题】:Adding Event Listener on button - Javascript在按钮上添加事件侦听器 - Javascript
【发布时间】:2018-03-29 18:40:13
【问题描述】:

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

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

按钮显示在每个信息窗口上,但是当我点击时什么都没有。

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 本文档 (developers.google.com/maps/documentation/javascript/examples/…) 表明您应该使用 addDomListener,而不是 addListener
  • 您正在创建一个新对象$(contentString)。试试$(infoWindow.getContent()).find("#btnDirection").addEventListener(....) 或者更好的$("body").on("click", "#btnDirection", function(){....})
  • 我对 event.addListener 没有任何问题。当我单击信息窗口上显示的按钮时,不起作用的是。
  • 我试过了。我现在知道 addEventListener 不是一个函数。
  • 第二个有效,但是当我单击其中一个按钮时,它正在对所有按钮执行操作,因为我正在向 infowindows 添加具有相同 ID 的按钮。你知道我该如何解决这个问题吗?

标签: javascript google-maps event-listener


【解决方案1】:

信息窗口的内容是异步添加到 DOM 中的,所以直到 InfoWindow "domready" 事件触发时才能找到它。

来自that documentation):

准备就绪 |参数:无
当包含 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

代码 sn-p:

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>

【讨论】:

    【解决方案2】:

    一种解决方案是:

    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>

    【讨论】:

    • 此解决方案适用于您在原始问题中发布的代码。如果您的页面中还有其他 id 为 btnDirection 的元素,那么它不会起作用,但这是另一回事。
    【解决方案3】:

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

    【讨论】:

    • 请详细解释您的问题?
    • 更重要的是,如果这确实是一个问题,请不要在答案中问它。请参阅how to ask 并提出一个新问题。
    【解决方案4】:

    当向 DOM 动态添加内容时(如 infoWindow-Content),您必须在事件绑定之前存在的父元素上注册 eventListener(例如 bodymap-容器)。

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

    google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(contentString);
        infoWindow.open(map, this);
    
        $('body').on('click', '#btnDirection', function() {
            console.log('Hello');
        });
    });
    

    第二个有效,但是当我单击其中一个按钮时,它正在对所有按钮执行操作,因为我正在向 infowindows 添加具有相同 ID 的按钮。你知道我该如何解决这个问题吗?

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

    【讨论】:

    • 你能给我更多的解释吗?如何使每个按钮的 id 唯一?为什么即使使用相同的 id 也能正常工作?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    • 2015-02-04
    • 2021-04-17
    • 2011-10-10
    相关资源
    最近更新 更多