如何在jquery中全局访问回调函数变量

时间:2014-01-27 09:54:56

标签: javascript php jquery

在此代码中:

$(document).ready(function() {
        var lat = 0;
        var lng = 0;
        function getLatLng(address) {
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({'address': address}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    lat = results[0].geometry.location.lat(); //how do I access lat 
                    lng = results[0].geometry.location.lng() //and lng outside function ormake it global
                }
            });
            alert(lat); // does not display only show's the 0
        }
        getLatLng();
    });

我希望alert(lat)显示lat不为零。

我该如何访问?

提前感谢!

3 个答案:

答案 0 :(得分:4)

在使用异步操作时,请考虑使用回调函数:

function getLatLng(address, callback) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'address': address}, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            lat = results[0].geometry.location.lat(); //how do I access lat 
            lng = results[0].geometry.location.lng() //and lng outside function ormake it global
            callback(lat, lng);
        }
    });
}

getLatLng(function(lat, lng) {
    alert([lat, lng]);
});

答案 1 :(得分:1)

您的alert打印0因为它在geocoder完成作业之前运行。您可以使用回调在geocoder完成时收到通知:

$(document).ready(function() {
    var lat = 0;
    var lng = 0;
    var geocoderFinished = function(){
        alert(lat);
    };
    function getLatLng(address) {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                lat = results[0].geometry.location.lat(); //how do I access lat 
                lng = results[0].geometry.location.lng() //and lng outside function ormake it global
                geocoderFinished();
            }
        });
    }
    getLatLng();
});

答案 2 :(得分:0)

这是因为alert(lat);在成功函数之前执行。您应该在回调函数内部发出警报或使用setTimeout并发出警报。

使用setTimeout是不好的做法,因为我们永远不知道执行服务器端调用需要多长时间。因此,更好的做法是在回调函数中调用代码以确保更改