简体   繁体   English

在javascript中设置内部作用域的外部作用域变量

[英]set outer scoped variable from inner scope in javascript

var lat = 0.0;
var lng = 0.0;
var jsonData = null;
var geocoder = new google.maps.Geocoder();
var miles = $('#milesAway').val();

// find what the user is locating by
if ($('#zipCode').is(':visible'))
{
    var zipText = $('#zipCode').val();
    if (isValidUSZip(zipText))
    {
        geocoder.geocode( {
            'address': zipText
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                lat = results[0].geometry.location.lat();
                lng = results[0].geometry.location.lng();
                map.setCenter(results[0].geometry.location);
            } else {
                alert("Zip Code couldn't be located.");
            }
        });
    }
    else
    {
        alert('Please enter a valid US zip code.');
    }
}

lat and lng are still set as 0.0 after this thing runs through, why? 这个东西经过后,lat和lng仍设为0.0,为什么? Shouldn't I be able to set these like this? 我不应该这样设置这些吗?

Edit: I get to the point where they are supposed to be set too, if I put an alert there I can see the values that they are supposed to be set to. 编辑:我到了应该设置它们的位置,如果我在那里发出警报,我可以看到他们应该设置的值。

The geocoder.geocode callback isn't running immediately, it's delayed until the AJAX call comes back. geocoder.geocode回调没有立即运行,它被延迟直到AJAX调用返回。 There's nothing wrong with the scope, the variables just won't be changed until the XHR is done. 范围没有任何问题,变量只有在XHR完成后才会改变。

If you're depending on them being changed, try putting your dependent code (or a call to a function) within the geocoder callback function. 如果您依赖于它们的更改,请尝试在地理编码器回调函数中放置相关代码(或调用函数)。

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

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