How to detect button click in googlemaps infowindow [duplicate]

天涯浪子 提交于 2021-02-04 18:48:08

问题


Using Googlemaps V3

I am trying to add a button to the infoWindow on my googlemap. The infoWindows and button appear as expected. I am trying to capture the onclick event of the button. This is what I have so far:

var contentBtn = '<p><button id="marker'+numby+'" class="iwLink" href="#" >Done</button></p>';
        google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent(address+contentBtn);
            infowindow.open(map, this);
        });

        google.maps.event.addDomListener(contentBtn, 'click', function() {

          alert($(this).attr('id'));
        });

The infoWindow appears as expected, along with the button. However, I also get the following error in the console log:

Uncaught TypeError: Cannot read property 'click' of undefined
This appears to be caused by the line google.maps.event.addDomListener(contentBtn, 'click', function()


回答1:


The button isn't added to the DOM until the infowindow completes rendering. You can't find it with getElementById (or the jquery equivalent) until after the infowindow domready event fires.

var contentBtn = '<p><button id="marker'+numby+'" class="iwLink" href="#" >Done</button></p>';
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(address+contentBtn);
        infowindow.open(map, this);
    });
    google.maps.event.addListener(infowindow, 'domready', function() {
      google.maps.event.addDomListener(contentBtn, 'click', function() {

        alert($(this).attr('id'));
      });
    });


来源:https://stackoverflow.com/questions/23187045/how-to-detect-button-click-in-googlemaps-infowindow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!