DIV onload 不触发 JavaScript 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13039654/
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 17:42:41  来源:igfitidea点击:

DIV onload Not Firing JavaScript Method

javascriptgoogle-maps-api-3asp.net-mvc-4

提问by Mike Perrenoud

I am using ASP.NET MVC 4 and I have a DIV like this:

我正在使用 ASP.NET MVC 4 并且我有一个这样的 DIV:

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

Then, in a JavaScript file (that I've verified is loaded) is the mapAddressfunction:

然后,在 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);
        }
    });
}

But for whatever reason it's not being called. Did I misunderstand the onloadevent?

但无论出于何种原因,它都没有被调用。我误解了onload事件吗?

Thanks all!

谢谢大家!

回答by Gabe

onloadwill not fire for a <div>element.

onload不会为<div>元素触发。

You can do that for the documentor body, or the less desired way of calling the script immediately after the <div>.

您可以为documentorbody或在<div>.

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

回答by geocodezip

onload is only supported by the following HTML Tags:

只有以下 HTML 标签支持 onload

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

回答by J. K.

Don't attach onloadhandlers to <div>elements, just the <body>element.

不要将onload处理程序附加到<div>元素,只是<body>元素。

A good place to put this is directly on the global object (window):

将 this 直接放在全局对象 ( window)上的一个好地方:

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

Placing an onloadhandler on a <div>doesn't make sense because the element is "loaded" right after it is parsed and added to the DOM tree.

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