首页 > 解决方案 > 尝试在 a 上执行 getElementById

  • 我在函数中创建的,返回 null
  • 问题描述

    我正在创建一个谷歌地图信息窗口,我想在其中放置一个可点击的文本来设置起点和终点。

    因此,我想将侦听器添加到我在窗口初始化中创建的文本中。

    在下面的代码中,showInfoWindow(marker)成功显示出现并且开始/结束文本在那里。

    但是,如果这是唯一存在的信息窗口,我会收到错误消息Uncaught TypeError: Cannot read property 'addEventListener' of null

    如果我调试,我无法获得之后的元素infoWindow.open(map, marker);(此时窗口实际上不可见),但是一旦窗口出现我就可以(在发生这种情况之前它会经历很多谷歌自己的本机代码)

    我什至尝试在调用的行之后添加侦听器,showInfoWindow(marker)但它仍然不起作用。

    function showInfoWindow(marker) {
    
    
         var infoWindow = new google.maps.InfoWindow({
        content: (marker.title 
          + '<br><img id="thumbnail" src = "img/' 
          + marker.title.toLowerCase() 
          + '.jpg"><br>'
          + '<ul>'
          + '<li id="infoWindowStart">Start from here</li>'
          + '<li id="infoWindowEnd">End here</li>'
          + '</ul>'
          )
    
      });
    
          infoWindow.open(map, marker);
    
       // then try to add a listener to the newly-created "infoWindowStart"
           document.getElementById("infoWindowStart").addEventListener("click",function(){
      console.log("We're going from here")
     });
    
    
    }
    

    标签: javascript

    解决方案


    domready当信息窗口附加到 DOM 时触发事件。所以你可以使用下面的代码。

    infoWindow.addListener("domready", function() {
      var infoWindowDom = document.getElementById("infoWindowStart");
      console.log(infoWindowDom); // check if it's loaded correctly
      infoWindowDom.addEventListener("click", function(){
        console.log("We're going from here")
      });
    });
    

    推荐阅读