一旦失效,变量值就会丢失

时间:2017-08-09 20:10:12

标签: javascript jquery

这是我写的一些代码来获取当地天气:

var temp;

function displayWeather(latitude, longitude) {
  var request = new XMLHttpRequest();
  // console.log(latitude);
  var method = 'GET';
  var url = 'https://fcc-weather-api.glitch.me/api/current?lon=' + longitude + '&lat=' + latitude;
  var async = true;
  request.open(method, url, async);
  request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
      var data = JSON.parse(request.responseText);
      // alert(request.responseText); // check under which type your city is stored, later comment this line
      var skyConditions = data.weather[0].description;
      $("#sky").html(skyConditions);
      temp = data.main.temp;
      $("#temp").html("<span id='tempNum'>" + Math.floor(temp) + "</span>" + "C");
      var icon = data.weather[0].icon;
      $("#icon").html("<img src=" + icon + ">");
      // alert(data.weather[0].main);
      if (data.weather[0].main == "Clouds") {
        $("body").addClass("cloudy");
      } else if (data.weather[0].main == "Rain") {
        $("body").addClass("rainy");
      } else if (data.weather[0].main == "Clear") {
        $("body").addClass("sunny");
      } else if (data.weather[0].main == "Thunderstorm") {
        $("body").addClass("thunder");
      }
    }
  };
  request.send();
};

我遇到的问题是分配给&#39; temp&#39;一旦它失去了功能就迷失了。所以,如果我打电话给'临时&#39;在代码中的其他地方,我得到了未定义而不是我在&#39; weatherDisplay&#39;中指定的值。我似乎无法摆脱烦恼;

0 个答案:

没有答案