繁体   English   中英

在页面加载时触发多个JavaScript函数

[英]Firing multiple javascript functions on page load

我设法创建了一个简单的地图,并在2个目的地之间标记了路线。 另外,我需要拉出距离值,然后对其进行一些基本的数学运算(乘以2)。 一切正常,但页面加载不起作用。 更准确地说,地图会在页面加载以及距离上显示,但是距离值不会被拉动,也不会乘以2。我设法使它可以在鼠标移动时工作,但这并不是完美的替代方法。

这是代码:

<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Directions</title>
    <link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet">
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&region=US"></script>
    <script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
    <script src="http://www.pengoworks.com/workshop/jquery/calculation/jquery.calculation.min.js" type="text/javascript"></script>
    <script>
        $(document).ready(function() {

            var rendererOptions = {
                draggable: false
            };
            var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
            var directionsService = new google.maps.DirectionsService();
            var map;

            function initialize() {

                var mapOptions = {
                    zoom: 7,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                };
                map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
                directionsDisplay.setMap(map);
                directionsDisplay.setPanel(document.getElementById('directionsPanel'));

                google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
                    computeTotalDistance(directionsDisplay.directions);
                });

                calcRoute();
            }

            function calcRoute() {

                var request = {
                    origin: 'Houston',
                    destination: 'Dallas',
                    travelMode: google.maps.DirectionsTravelMode.DRIVING
                };
                directionsService.route(request, function(response, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setDirections(response);
                    }
                });
            }

            function computeTotalDistance(result) {
                var total = 0;
                var myroute = result.routes[0];
                for (var i = 0; i < myroute.legs.length; i++) {
                    total += myroute.legs[i].distance.value;
                }
                total = total / 1000.
                document.getElementById('total').innerHTML = total + ' km';
            }

            google.maps.event.addDomListener(window, 'load', initialize);


            function stripint() {
                var val = $('[jsdisplay=distance]').text(); // get text content of <span jstcache="7">

                // Replace using regex instead of strings, to catch more than the first match
                val = val.replace(/\./g, "");
                val = val.replace(/,/g, ".");
                val = val.replace(/_/g, ",");

                $('#dist').val(val);
            }

            function recalc() {

                $("[id^='total_price_ht']").calc(
                // the equation to use for the calculation
                "di * 10", {
                    bind: "keyup",
                    di: $("[id^='dist']")
                }, function(s) {
                    // return the number as a dollar amount
                    return "$" + s.toFixed(2);
                });
            }

            $('#content').mousemove(function() {
                stripint();
                recalc();
            });

            stripint();
            recalc();
        });
    </script>
</head>

<body>
    <div id="content">
        <p>Distance: <span id="total"></span>

        </p>
        <input type="text" value="0" name="dist" id="dist" />
        <div id="total_price_ht_0" class="price">$0.00</div>
        <div id="map-canvas" style="width:100%; height:500px"></div>
        <div id="directionsPanel" style="width:100%; height:auto"></div>
    </div>
</body>

首先,您不需要使用$(document).ready()因为您已经将Initialize函数绑定到了窗口onLoad事件google.maps.event.addDomListener(window, 'load', initialize);

您需要等待直到计算出方向和距离,您才真正不需要从directionsPanel读取它,您可以直接从API响应中读取所需的任何内容。

像这样在calcRoute使用回调:

directionsService.route(request, function(response, status) {
  if (status == google.maps.DirectionsStatus.OK) {
    directionsDisplay.setDirections(response);
    dist = response.routes[0].legs[0].distance.text;
    stripint(dist);
    recalc();
  }
});

您还需要在您的strprint添加dist参数:

function stripint(val) {

  // Replace using regex instead of strings, to catch more than the first match
  val = val.replace(/\./g, "");
  val = val.replace(/,/g, ".");
  val = val.replace(/_/g, ",");

  $('#dist').val(val);
}

因此您的新代码不会使用document.ready并在API响应时立即计算价格。

新的<script>标记:

var rendererOptions = {
    draggable: false
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {

    var mapOptions = {
        zoom: 7,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
    };
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById('directionsPanel'));

    google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {
        computeTotalDistance(directionsDisplay.directions);
    });

    calcRoute();
}

function calcRoute() {

    var request = {
        origin: 'Houston',
        destination: 'Dallas',
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            dist = response.routes[0].legs[0].distance.text;
            stripint(dist);
            recalc();
        }
    });
}

function computeTotalDistance(result) {
    var total = 0;
    var myroute = result.routes[0];
    for (var i = 0; i < myroute.legs.length; i++) {
        total += myroute.legs[i].distance.value;
    }
    total = total / 1000.
    document.getElementById('total').innerHTML = total + ' km';
}

google.maps.event.addDomListener(window, 'load', initialize);


function stripint(val) {

    // Replace using regex instead of strings, to catch more than the first match
    val = val.replace(/\./g, "");
    val = val.replace(/,/g, ".");
    val = val.replace(/_/g, ",");

    $('#dist').val(val);
}

function recalc() {

    $("[id^='total_price_ht']").calc(
        // the equation to use for the calculation
        "di * 10", {
            bind: "keyup",
            di: $("[id^='dist']")
        }, function (s) {
            // return the number as a dollar amount
            return "$" + s.toFixed(2);
        });
}

这里不需要两个标签; 您可以将所有内容都放入其中。 您的某些函数使用jQuery选择器,尝试将所有选择器都放在$(document).ready()中,这将确保在调用它们时所有选定元素都可用:

$(document).ready(function(){

  //Insert your functions with selectors here

});

这是document.ready中所有内容的重新排列的代码: http : //jsbin.com/iqejiy/1/edit

希望能帮助到你。

我认为您在这里缺少document.ready()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM