简体   繁体   English

如何在其他函数的函数下使用javascript中定义的变量。 以下是我的确切Javascript代码

[英]How can I use variables defined in javascript under functions in other functions. below is my exact Javascript Code

var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    lat = position.coords.latitude;
    lon = position.coords.longitude;
    $(".demo").append("Latitude: " + position.coords.latitude +
        "<br>Longitude: " + position.coords.longitude);
}
var gettingJSON = function() {

    $.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "APPID=4a74787aeb02dcb53dcc8c15e29bdfa1", function(json) {
        $(".para").append(JSON.stringify(json));
    });
}

$(document).ready(function() {
    getLocation();
    gettingJSON();
});

Above is my Code I'm getting the following error 以上是我的代码,出现以下错误

jQuery.Deferred exception: lat is not defined ReferenceError: lat is not defined
    at gettingJSON (file:///G:/WebDev/WeatherAPI/js/main.js:19:73)
    at HTMLDocument.<anonymous> (file:///G:/WebDev/WeatherAPI/js/main.js:26:1)
    at j (file:///G:/WebDev/WeatherAPI/js/jquery.min.js:2:29948)
    at k (file:///G:/WebDev/WeatherAPI/js/jquery.min.js:2:30262) undefined
r.Deferred.exceptionHook @ jquery.min.js:2
k @ jquery.min.js:2
jquery.min.js:2 Uncaught ReferenceError: lat is not defined
    at gettingJSON (main.js:19)
    at HTMLDocument.<anonymous> (main.js:26)
    at j (jquery.min.js:2)
    at k (jquery.min.js:2)
gettingJSON @ main.js:19
(anonymous) @ main.js:26
j @ jquery.min.js:2
k @ jquery.min.js:2

The Code is not Working. 该代码不起作用。 I'm trying to get use lat and lon from the showPosition Fucntion, but it saying that lat and lon are not defined. 我试图从showPosition Fucntion中使用lat和lon,但是它说lat和lon没有定义。 I had made lat and lon global variables by not using var keyword. 我通过不使用var关键字制作了lat和lon全局变量。 but they are not working. 但他们没有工作。 please anyone help me. 请任何人帮助我。

If you want to access those variables I'd recommend returning them from the function. 如果要访问这些变量,建议您从函数中返回它们。 Or you could do the same thing using class objects. 或者,您可以使用类对象执行相同的操作。

I think I've found the issue- 我想我发现了问题-

Your getLocation() function doesn't populate lat and lon fast enough, So when gettingJSON() is called lat and lon don't exist yet. 您的getLocation()函数无法足够快地填充lat和lon,因此当getJSON()称为lat和lon时尚不存在。

I've tested it with a 5 sec wait here- 我已经在这里等待了5秒钟,对它进行了测试-

$(document).ready(function(){
    getLocation();  
    gettingJSON();
    //checking lon and lat immediatelly
    console.log("lon:"+lon+ "lat:"+ lat);
    //setting a 5 sec timeout, and checking the lon and lat value again
    setTimeout(function(){ 
        console.log('waiting');
        console.log("lon:"+lon+ "lat:"+ lat);
        }, 5000); 
});

console log: 控制台日志:

lon: undefined lat: undefined
after wait:
lon: 34.99041030000001 lat: 32.7888574

This is probably because the user doesn't allow the location check fast enough. 这可能是因为用户不允许足够快的位置检查。

Maybe try changing the code like this: 也许尝试像这样更改代码:

function showPosition(position) {
  lat=position.coords.latitude;
  lon=position.coords.longitude;
  $(".demo").append("Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude); 
  gettingJSON(); //calling gettingJSON here assures that you already have the coordinates
}

Generally, for you to access a variable in all functions, they should have a global scope. 通常,要访问所有函数中的变量,它们应具有全局作用域。 This means that they are declared outside the functions. 这意味着它们在函数外部声明。

Your lat and lon function are declared locally inside the showPosition(position) . 您的latlon函数在showPosition(position)内部局部声明。 This means that they can only be accessed by the showPosition(position) function and not the gettingJSON() function. 这意味着它们只能由showPosition(position)函数访问,而不能由gettingJSON()函数访问。

It should work if you declare var lat=position.coords.latitude; 如果您声明var lat=position.coords.latitude;应该会起作用var lat=position.coords.latitude; and lon=position.coords.longitude; lon=position.coords.longitude; outside and before the showPosition(position) function. showPosition(position)函数之前和之后。

If you are working on freecodecamp, here is a link where global and local variable scope are explained. 如果您在freecodecamp上工作,那么这里是解释全局和局部变量作用域的链接。 FreeCodeCamp: Global Scope , FreeCodeCamp: Local Scope , FreeCodeCamp: Global vs Local Scope FreeCodeCamp:全局范围FreeCodeCamp:本地范围FreeCodeCamp:全局vs本地范围

In addition, you did not call the showPosition(position) function remember to do this after adjusting your variable declaration as indicated by one of the comments 另外,您没有调用showPosition(position)函数,切记在调整变量声明(如注释之一所示)后执行此操作

I hope this helps. 我希望这有帮助。

Put it all into a self-executing function and then declare your variables at the beginning. 将所有内容放入自执行函数中,然后在开始时声明变量。 That way, they're not GLOBAL (you generally don't want to make variables GLOBAL) but they're available to everything in your code: 这样,它们不是GLOBAL(您通常不希望将变量设置为GLOBAL),但是它们可用于代码中的所有内容:

(function($){
  var lat, lon, x;

  function getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition);
    } else {
      x.innerHTML = "Geolocation is not supported by this browser.";
    }
  }

  function showPosition(position) {
    lat = position.coords.latitude;
    lon = position.coords.longitude;
    $(".demo").append("Latitude: " + position.coords.latitude +
      "<br>Longitude: " + position.coords.longitude);
  }

  var gettingJSON = function() {
    $.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "APPID=4a74787aeb02dcb53dcc8c15e29bdfa1", function(json) {
      $(".para").append(JSON.stringify(json));
    });
  }

  $(document).ready(function() {
    x = document.getElementById("demo");
    getLocation();
    gettingJSON();
  });

})(jQuery);

To ensure you do get the values of lat, long you could consider changing the structure of your program, and call gettingJSON inside showPosition: 为了确保您确实获得了lat的值,可以考虑长时间更改程序的结构,并 showPosition中调用gettingJSON:

var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    lat = position.coords.latitude;
    lon = position.coords.longitude;
    $(".demo").append("Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude);

    //call gettingJson here, pass it lat, lon values...sure to work if lat,lon is in fact gettting populated.
    gettingJSON(lat, lon);

}
var gettingJSON = function(lat, lon) {

$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "APPID=4a74787aeb02dcb53dcc8c15e29bdfa1", function(json) {
    $(".para").append(JSON.stringify(json));
    });
}

$(document).ready(function() {
    getLocation();
});

暂无
暂无

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

相关问题 JavaScript / jQuery:一个ID,两个功能。 如何以最少的代码重复做到这一点? - JavaScript/jQuery : One ID, two functions. How can I do this with minimal code duplication? 您可以使用javascript函数创建其他函数。 这是如何运作的? - You can have javascript functions that create other functions. How does this work? 我正在尝试使用javascript函数更改html链接的样式。 为什么我的代码不起作用? - I am trying to change the style of a html link with javascript functions. Why does my code not work? Javascript指南 - 将onclick更改为onkeypress-如何使用空格键进行两种功能。 关闭导航并打开 - Javascript guide - change onclick to onkeypress— how can I use the space key for both functions. To close the nav and open 如何改进我对多个 JavaScript 函数的调用。 程序有效,但是我想要一种更流畅的方式来处理这些功能 - How to improve my calling of multiple JavaScript functions. Program works however I would like a smoother way of handling these functions 如何在特定控制器下访问资产javascript中定义的jQuery函数以适应js.erb扩展? - How can i access jquery functions defined in assets javascript foler to my js.erb extention under specific controller? 如何在另一个Javascript文件中使用游戏对象及其功能/变量 - How can I use my game object and its functions/variables in another Javascript File 异步加载JavaScript函数。 - Asynchronous loading JavaScript functions. 如何重用我的代码 javascript 的功能? - how can I reuse the functions of my code javascript? 您如何查看javascript当前定义了哪些函数和变量? - How can you see what functions and variables are currently defined in javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM