javascript - 尝试对我在函数中创建的 <li> 执行 getElementById 返回 null

标签 javascript

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

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

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

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

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

我什至尝试在调用 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")
 });


}

最佳答案

当信息窗口附加到 DOM 时,会触发

domready 事件。 所以你可以使用下面的代码。

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

关于javascript - 尝试对我在函数中创建的 <li> 执行 getElementById 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56329670/

相关文章:

javascript - jQuery 砌体示例对我不起作用

javascript - 如何在 JSFiddle 上创建具有可调整大小的行和列(如 HTML、CSS、JS 框)的表格?

javascript - 用jquery高亮textarea边框一段时间

Javascript onchange函数执行onload但不执行onchange

javascript - 更改矢量形状的颜色 - Photoshop

javascript - 使用indexOf获取数组集合中数组的索引(Javascript)

javascript - 如何使用 require js shim 加载 google map 依赖项?

javascript - 嵌入代码不会显示在 WordPress 页面中

javascript - JQUERY AJAX ---- 出于可用性原因暂停但仅在必要时暂停?

javascript - vue.js 模板中的语言特殊字符编码错误