javascript - 尝试在 a 上执行 getElementById
问题描述
我正在创建一个谷歌地图信息窗口,我想在其中放置一个可点击的文本来设置起点和终点。
因此,我想将侦听器添加到我在窗口初始化中创建的文本中。
在下面的代码中,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")
});
}
解决方案
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")
});
});
推荐阅读
- r - 什么是 R 相当于 Stata 的填充?
- php - 对按时间段分桶的聚合数据发出请求时,将忽略使用 GoogleFit REST API 时区
- r - 如何使用 R-studio 在 R 中创建概率图
- c# - Request.AcceptTypes 的 ASP.Net Core 类似物是什么?
- excel - 如何搜索特定的行、列值然后返回行号?
- node.js - Nodejs 无法响应多个猫鼬连接测试请求
- bash - 如何推迟打印错误,直到每次执行
- javascript - 打开时 Material Dropdown 组件的 Z-Index 不在固定 div 下分层
- ios - Xcode 只生成通用的 xcode 存档
- node.js - 如何使用带有 Node 的繁琐驱动程序来处理错误