2012-10-23 323 views
2

我使用ASP.NET MVC 4 JavaScript方法,我有這樣一個DIV:DIV onload事件不觸發

<div id="map_canvas" style="width: 500px; height: 400px;" onload="mapAddress();"></div> 

然後,在JavaScript文件(,我已經驗證加載)被mapAddress功能:

function mapAddress() { 
    //In this case it gets the address from an element on the page, but obviously you could just pass it to the method instead 
    var address = $("#Address").val(); 

    geocoder.geocode({ 'address': address }, function (results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      var myLatLng = results[0].geometry.location.LatLng; 

      var mapOptions = { 
       center: myLatLng, 
       zoom: 15, 
       mapTypeId: google.maps.MapTypeId.ROADMAP 
      }; 

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

      var marker = new google.maps.Marker({ 
       position: myLatLng, 
       map: map, 
       title: $("#Name").val() + " Location" 
      }); 
     } 
     else { 
      alert("The location of the event could not be mapped because: " + status); 
     } 
    }); 
} 

但是,無論什麼原因,它不被稱爲。我誤解了onload事件嗎?

謝謝大家!

回答

9

onload將不會觸發<div>元素。

您可以對documentbody執行此操作,或者在<div>之後立即調用腳本。

<div id="map_canvas" style="width: 500px; height: 400px;"></div> 
<script> 
mapAddress(); 
</script> 
+2

謝謝,這個工作就像一個魅力。對不起,我的無知!有時候你想知道,你已經做了十多年,並且仍然在這裏和那裏想念這樣的事情。只是證明我們並不完美。 –

1

請勿將onload處理程序添加到<div>元素,只需要<body>元素。

一個好地方,把這個直接是全局對象(window)上:

window.onload = function() { 
    // your code 
}; 

<div>放置一個onload處理程序沒有任何意義,因爲該元素是「裝」的權利是後解析並添加到DOM樹中。