javascript 无法获取属性“offsetWidth”的值:对象为空或未定义错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9747557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:41:51  来源:igfitidea点击:

Unable to get value of the property 'offsetWidth' : object is null or undefined error

javascriptgoogle-mapsgoogle-maps-api-3

提问by user1275351

I am developing a page that is basically being set up as a table with three rows. The the top row is the header, the middle row is the main part of the page, and the bottom row is the navigation. Each button in the navigation row fires off a javascript function which using the innerHTML value of the middle row and places the necessary html to show the contents of the page. On the main page I have:

我正在开发一个基本上被设置为三行表格的页面。顶行是页眉,中行是页面的主要部分,底行是导航。导航行中的每个按钮都会触发一个 javascript 函数,该函数使用中间行的 innerHTML 值并放置必要的 html 以显示页面内容。在主页上我有:

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=MY_KEY&sensor=false"></script>

In the head section I have:

在头部部分,我有:

var myOptions = {center: new google.maps.LatLng(-34.397, 150.644), zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP };

In the body section so that it runs right away and then in the function that is called by the MAP Button I have:

在正文部分,以便它立即运行,然后在 MAP 按钮调用的函数中,我有:

var mapString;
var w = document.getElementById("mainwindow");
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
mapString = '<table width="1024" cellpadding="0" cellspacing="0"><tr>';
mapString += '<td> <div id="map_canvas" width="1024" height="350"></div></td>';
mapString += '</tr></table>';
w.innerHTML = mapString;

Now when I press the Map button I get the error:

现在,当我按下 Map 按钮时,出现错误:

Unable to get value of the property 'offsetWidth': object is null or undefined
main.js Line 29
Code 0 char:1385
URI: http://maps.gstatic.com/intl/en_us/mapfiles/api-2/3/2/main.js

Not sure what this error is trying to tell me. Any help would be greatly appreciated.

不确定这个错误试图告诉我什么。任何帮助将不胜感激。

回答by Silviu-Marian

do the

   var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

last because map_canvasdiv doesn't exist when google maps attempts to load the map into that div.

最后是因为map_canvas当谷歌地图尝试将地图加载到该 div 时,div 不存在。

should read like this

应该这样读

var mapString;
var w = document.getElementById("mainwindow");
mapString = '<table width="1024" cellpadding="0" cellspacing="0"><tr>';
mapString += '<td> <div id="map_canvas" width="1024" height="350"></div></td>';
mapString += '</tr></table>';
w.innerHTML = mapString;

var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);