我正在创建一个 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/