2

ASP.NET MVC 4を使用していて、次のようなDIVがあります。

<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イベントを誤解しましたか?

皆さんありがとう!

4

3 に答える 3

11

onload<div>要素に対しては起動しません。

documentまたはbody、またはの直後にスクリプトを呼び出すあまり望ましくない方法に対してこれを行うことができます<div>

<div id="map_canvas" style="width: 500px; height: 400px;"></div>
<script>
 mapAddress();
</script>
于 2012-10-23T21:38:56.390 に答える
3

onloadは、次のHTMLタグでのみサポートされます

<body>, <frame>, <frameset>, <iframe>, <img>, 
<input type="image">, <link>, <script>, <style>
于 2012-10-23T21:57:29.633 に答える
1

onloadハンドラーを<div>要素にアタッチしないでください。要素のみをアタッチしてください<body>

windowこれを配置するのに適した場所は、グローバルオブジェクト( )に直接配置することです。

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

要素が解析されてDOMツリーに追加された直後に要素が「ロード」されるため、onloadハンドラーをに配置しても意味がありません。<div>

于 2012-10-23T21:38:28.680 に答える