简体   繁体   English

JavaScript代码无法执行

[英]Javascript code wont execute

I have a very basic code to load Bing maps. 我有一个非常基本的代码来加载必应地图。 By placing this code in the head section of an HTML, it will load the map inside a div #map. 通过将此代码放置在HTML的头部,它将在div #map中加载地图。

This will work fine: 这将正常工作:

<script type="text/javascript">
         window.onload = GetMap;               
         function GetMap()
         {
            map = new VEMap('map');
            map.LoadMap();            
         }
         </script>

As the above code simply loads the function GetMap. 上面的代码只是加载了GetMap函数。 So shouldn't the code inside the function work without using function as well? 因此,如果不使用函数,函数内部的代码是否也不能正常工作? For example: 例如:

<script type="text/javascript">
            map = new VEMap('map');
            map.LoadMap();
        </script>

But why this would not work? 但是为什么这行不通呢?

If you place it in the head section, it will execute before whole page is rendered and "map" div is created. 如果将其放在头部,它将在呈现整个页面和创建“ map” div之前执行。 This will cause errors when trying to change the div contents. 尝试更改div内容时,这将导致错误。

By wrapping it in function and calling that function on window load, you ensure that the code is executed only after page is fully rendered. 通过将其包装在函数中并在窗口加载时调用该函数,可以确保仅在页面完全呈现后才执行代码。

Alternatively you could just place your code after the div, then it should work. 另外,您也可以将代码放在div之后,然后它应该可以工作。

I'm assuming that Bing maps binds to a DOM element to show the map (just like Google maps). 我假设Bing地图绑定到DOM元素以显示地图(就像Google地图一样)。 If that's the case that DOM element must first be loaded by the browser for the binding to work. 如果是这种情况,则必须先由浏览器加载DOM元素,绑定才能起作用。 Loading it on window.load ensures that this happens. 将其加载到window.load可以确保发生这种情况。 I'm sure your code should work if you move it to the bottom of the page, just above the body tag. 如果将代码移动到页面底部, body标记上方,我确定您的代码可以使用。

It doesn't work because the map element doesn't exist in the DOM when you call 它不起作用,因为调用时map元素在DOM中不存在

map = new VEMap('map');

The window onload event fires at the end of the document loading process - so all objects in the document are in the DOM. 窗口onload事件在文档加载过程结束时触发-因此文档中的所有对象都在DOM中。

长话短说:如果您不喜欢函数(对您做了什么?!),请将第二个脚本放在body元素的底部

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM