如何从HTML调用Javascript

How to call Javascript from HTML

本文关键字:调用 Javascript HTML      更新时间:2023-09-26

我在JSFiddle上找到了一点Google Maps Javascript:http://fiddle.jshell.net/bTujZ/885/

我试图通过在脚本标签之间包含脚本,然后在正文中调用它来运行,像这样:

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

当我尝试加载页面时,它是空白的。

完整代码如下:

<html>
<head>
<script language="javascript">
var points = [
    ['name1', 59.9362384705039, 30.19232525792222, 12, 'www.google.com'],
    ['name2', 59.941412822085645, 30.263564729357767, 11, 'www.amazon.com'],
    ['name3', 59.939177197629455, 30.273554411974955, 10, 'www.stackoverflow.com']
];
function setMarkers(map, locations) {
    var shape = {
        coord: [1, 1, 1, 20, 18, 20, 18 , 1],
        type: 'poly'
    };
    for (var i = 0; i < locations.length; i++) {
        var flag = new google.maps.MarkerImage(
            'http://googlemaps.googlermania.com/google_maps_api_v3/en/Google_Maps_Marker.png',
            new google.maps.Size(37, 34),
            new google.maps.Point(0,0),
            new google.maps.Point(0, 19)
        );
        var place = locations[i];
        var myLatLng = new google.maps.LatLng(place[1], place[2]);
        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            icon: flag,
            shape: shape,
            title: place[0],
            zIndex: place[3],
            url: place[4]
        });
        google.maps.event.addListener(marker, 'click', function() {
            alert('go to ' + this.url);
            //window.location.href = this.url;
        });
    } 
}
function initialize() {
    var myOptions = {
        center: new google.maps.LatLng(59.91823239768787, 30.243222856188822),
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    setMarkers(map, points);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:400px; height:400px"></div>
</body>
</html>

我确定我犯了一个愚蠢的错误,因为我是Javascript的新手。

你在哪里加载API?

这里有一种方法。https://developers.google.com/maps/documentation/javascript/examples/map-simple-async

尝试使用jquery (http://www.jquery.com)

http://api.jquery.com/ready/

$( document ).ready(function() {
// Handler for .ready() called.
});

相当于调用(不使用jquery):

$(function() {
// Handler for .ready() called.
});

我更喜欢使用jquery,因为ready文档内部的分析依赖于浏览器引擎。

可能的副本:$(document)。