网页html错误:Uncaught TypeError: Cannot read property 'addEventListener' of null

 1 function openInfo(content,e){
 2   var p = e.target;
 3   content = content+'<br/>坐标 : <br/>'+p.getPosition().lng+'&nbsp;'+p.getPosition().lat;
 4   content = content+"<br/><Button id='startPoint'>设为起点</Button>";
 5   content = content+"&nbsp;&nbsp;&nbsp;&nbsp;<Button id='endPoint'>设为终点</Button>";
 6   var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
 7   var infoWindow = new BMap.InfoWindow(content,opts);      // 创建信息窗口对象
 8   map.openInfoWindow(infoWindow,point);                    //开启信息窗口
9 但是会发生报错:Uncaught TypeError: Cannot read property 'addEventListener' of null 10 影响就是第一次渲染监听不到,而后果就是点击的第一次无法监听,点击无效。 11 12 上网搜了很久也没有解决办法,其实这时候用延时监听就可以了!!! 13 14 我的代码写成这样 15 16 window.setTimeout(function() { 17 document.getElementById('startPoint').addEventListener('click', function() { 18 console.log(p.getPosition()); 19 startLng = p.getPosition().lng; 20 startLat = p.getPosition().lat; 21 map.closeInfoWindow(); 22 }, false); 23 document.getElementById('endPoint').addEventListener('click', function() { 24 endLng = p.getPosition().lng; 25 endLat = p.getPosition().lat; 26 route(); 27 }, false); 28 }, 500); 29 也就是在监听的时间中添加延时监听函数 30 window.setTimeout(function() { 31 }, 500);
原文地址:https://www.cnblogs.com/aivnfjgj/p/12590212.html