【问题标题】:jQuery Global variable value out of function [duplicate]jQuery全局变量值超出功能[重复]
【发布时间】:2016-06-30 06:56:21
【问题描述】:
var hhhhhhh = '';
        function displayLocation(latitude, longitude) {
            var request = new XMLHttpRequest();

            var method = 'GET';
            var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&sensor=true';
            var async = true;

            request.open(method, url, async);
            request.onreadystatechange = function () {
                if (request.readyState == 4 && request.status == 200) {
                    var data = JSON.parse(request.responseText);
                    var addressComponents = data.results[0].address_components;
                    for (i = 3; i < 4; i++) {
                        hhhhhhh = addressComponents[i].long_name;
                    }
                }
            };
            request.send();
        }
        console.log(hhhhhhh);

var hhhhhhh 没有从 displayLocation 函数中获取任何值。在控制台中,函数外部为 null,而函数内部获取其值。请帮忙。谢谢

【问题讨论】:

  • console.log(hhhhhhh)var hhhhhhh = '' 之后立即执行。您必须调用该函数,然后输出变量的值

标签: jquery geolocation


【解决方案1】:

你必须在 console.log 输出之前调用你的函数

var hhhhhhh = '';
function displayLocation(latitude, longitude) {
  //your code
   hhhhhhh = "Value";
}
displayLocation(0, 0);
console.log(hhhhhhh);

【讨论】:

  • 感谢您的快速响应,先生。但仍然存在问题。现在当我调用该函数时,出现错误“未捕获的参考错误:未定义纬度”。有什么解决方案吗?很抱歉,我正处于学习阶段。
  • 调用函数时可能没有正确传递经纬度值
【解决方案2】:

你需要调用函数然后控制台值:

var hhhhhhh = ''; 功能显示位置(纬度,经度){ var request = new XMLHttpRequest();

            var method = 'GET';
            var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&sensor=true';
            var async = true;

            request.open(method, url, async);
            request.onreadystatechange = function () {
                if (request.readyState == 4 && request.status == 200) {
                    var data = JSON.parse(request.responseText);
                    var addressComponents = data.results[0].address_components;
                    for (i = 3; i < 4; i++) {
                        hhhhhhh = addressComponents[i].long_name;
                    }
                }
            };
            request.send();
        }

   displayLocation(lat,long) //  you need to call the function and then console the value

        console.log(hhhhhhh);

【讨论】:

  • 感谢您的快速响应,先生。但仍然存在问题。现在当我调用该函数时,出现错误“未捕获的参考错误:未定义纬度”。有什么解决方案吗?很抱歉,我正处于学习阶段。
猜你喜欢
  • 1970-01-01
  • 2023-03-04
  • 2022-01-28
  • 1970-01-01
  • 1970-01-01
  • 2020-09-22
  • 2016-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多