DIV onload不会触发JavaScript方法

时间:2012-10-23 21:34:04

标签: javascript google-maps-api-3 asp.net-mvc-4

我正在使用ASP.NET MVC 4,我有这样的DIV:

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

然后,在mapAddress函数的JavaScript文件中(我已验证已加载):

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事件?

全部谢谢!

3 个答案:

答案 0 :(得分:9)

onload不会触发<div>元素。

您可以针对documentbody执行此操作,或者在<div>之后立即调用脚本的方式。

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

答案 1 :(得分:3)

onload is only supported by the following HTML Tags

<body>, <frame>, <frameset>, <iframe>, <img>, 
<input type="image">, <link>, <script>, <style>

答案 2 :(得分:1)

请勿将onload个处理程序附加到<div>元素,而只附加<body>元素。

放置它的好地方直接放在全局对象(window)上:

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

onload上放置<div>处理程序没有意义,因为该元素在解析并添加到DOM树后立即被“加载”。