0

我收到错误 Uncaught ReferenceError: mapCenterAt is not defined with the following script:

<script>
jQuery(document).ready(function ($) {

    // Map Markers
    var mapMarkers = [{
        address: "217 Summit Boulevard, Birmingham, AL 35243",
        html: "<strong>Alabama Office</strong><br>217 Summit Boulevard, Birmingham, AL 35243<br><br>
        <a href='#' onclick='mapCenterAt({latitude: 33.44792, longitude: -86.72963, zoom: 16}, event)'>[+] zoom here</a>",
        icon: {
            image: "img/pin.png",
            iconsize: [48, 48],
            iconanchor: [48, 48]
        }
    }];

    // Map Initial Location
    var initLatitude = 37.09024;
    var initLongitude = -95.71289;

    // Map Extended Settings
    var mapSettings = {
        controls: {
            panControl: true,
            zoomControl: true,
            mapTypeControl: true,
            scaleControl: true,
            streetViewControl: true,
            overviewMapControl: true
        },
        scrollwheel: false,
        markers: mapMarkers,
        latitude: initLatitude,
        longitude: initLongitude,
        zoom: 5
    };

    var map = $("#googlemaps").gMap(mapSettings);

    // Map Center At
    var mapCenterAt = function(options, e) {
        e.preventDefault();
        $("#googlemaps").gMap("centerAt", options);
    }
});
</script>   

mapCenterAt 在脚本底部定义,但是在页面上执行 onclick 时会引发错误。mapCenterAt 是否需要以不同的方式定义才能与 onclick 一起使用?

4

1 回答 1

0

jQuery 的文档就绪处理程序创建了一个不同的范围,因此mapCenterAt内联 onclick 处理程序无法使用该函数,因为它位于全局范围内,比文档就绪的范围更高。

您要么必须使用全局范围:

window.mapCenterAt = function(options, e) {
    e.preventDefault();
    $("#googlemaps").gMap("centerAt", options);
}

或创建一个适当的事件处理程序:

<script>
jQuery(document).ready(function ($) {
    // Map Markers
    var mapMarkers = [{
        address: "217 Summit Boulevard, Birmingham, AL 35243",
        html: "<strong>Alabama Office</strong><br>217 Summit Boulevard, Birmingham, AL 35243<br><br><a href='#' id='mapButton'>[+] zoom here</a>",
        icon: {
            image: "img/pin.png",
            iconsize: [48, 48],
            iconanchor: [48, 48]
        }
    }];

    // Map Initial Location
    var initLatitude = 37.09024;
    var initLongitude = -95.71289;

    // Map Extended Settings
    var mapSettings = {
        controls: {
            panControl: true,
            zoomControl: true,
            mapTypeControl: true,
            scaleControl: true,
            streetViewControl: true,
            overviewMapControl: true
        },
        scrollwheel: false,
        markers: mapMarkers,
        latitude: initLatitude,
        longitude: initLongitude,
        zoom: 5
    };

    var map = $("#googlemaps").gMap(mapSettings);

    $(document).on('click', '#mapButton', function(e) {
        e.preventDefault();
        $("#googlemaps").gMap("centerAt", {latitude: 33.44792, longitude: -86.72963, zoom: 16});
    });
});
</script>   
于 2013-08-21T18:09:14.170 回答