window.onload工作,但Chrome控制台说:未捕获的TypeError:window.onload不是一个函数

时间:2015-04-28 18:54:32

标签: javascript asp.net-mvc

我想在页面加载时运行window.onload(getLocation());方法。我添加了 Uncaught TypeError: window.onload is not a function(anonymous function) @ (index):116 并按我的意愿调用了该功能,但Chrome控制台说:

window.onload(getLocation());

视图,@{ ViewBag.Title = "Home Page"; } <div id="demo"></div> <h2>Gecoding Demo JavaScript: </h2> <div id="map" style="height: 253px ; width: 253px" /> @section Scripts { <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> <script> var x = document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { var position = navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude; InitializeMap(position) } var map; var geocoder; function InitializeMap(position) { alert(position.coords.latitude+""); var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); var myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP, disableDefaultUI: true }; map = new google.maps.Map(document.getElementById("map"), myOptions); } window.onload(getLocation()); </script> } 位于底部:

NSMutableArray * brokenCars = [NSMutableArray arrayWithObjects:
                              @"Audi A6", @"BMW Z3",
                              @"Audi Quattro", @"Audi TT", nil];
[brokenCars removeObjectAtIndex:2];

1 个答案:

答案 0 :(得分:8)

你编写代码的方式,它没有运行onload,它只是在解析器命中时运行。因为您编写了getLocation()而不仅仅是getLocation,所以它会执行函数。

如果您确定在加载时没有其他任何内容可以解决,您可以执行window.onload=getLocation;。如果您想确保与可能使用load事件的其他代码(包括第三方框架/库)很好地协作,您可以执行以下操作:

window.addEventListener('load', getLocation);

请注意,该代码在IE8中不起作用。如果您需要支持IE8,请检查addEventListener(),如果找不到,请检查并使用attachEvent()代替:

   if (window.addEventListener) {
      window.addEventListener('load', getLocation);
   } else if (window.attachEvent) {
      window.attachEvent('onload', getLocation);
   } else { 
      window.onload = getLocation;
   }