简体   繁体   English

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

[英]How to access callbak function variable globally in jquery

In this code: 在此代码中:

$(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();
    });

I want the alert(lat) to show the lat not zero. 我希望alert(lat)显示纬度不为零。

how can I access this? 我该如何访问呢?

thanks in advance! 提前致谢!

Consider using callback function when you work with asynchronous operations: 处理异步操作时,请考虑使用回调函数:

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]);
});

Your alert prints 0 because it is run before geocoder finishes its job. 您的alert 0因为它是在geocoder完成其工作之前运行的。 You can use callback to be notified when geocoder finishes: 您可以使用回调在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();
});

It is because alert(lat); 这是因为alert(lat); is getting executed before the success function. 在成功功能之前被执行。 You should be alerting it either inside callback function or use setTimeout and give the alert. 您应该在回调函数内部或使用setTimeout发出警报,并发出警报。

it is bad practise to use setTimeout as we never know how long it will take to execute server side call. 使用setTimeout是一种不好的做法,因为我们永远不知道执行服务器端调用将花费多长时间。 So its better practise to call the code in callback function to ensure the changes 因此,最好的做法是在回调函数中调用代码以确保更改

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

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