【问题标题】:Javascript variable scope issue between functions [duplicate]函数之间的Javascript变量范围问题[重复]
【发布时间】:2016-03-27 13:32:27
【问题描述】:

我有以下代码:

var currentTemp = 0;
  $.simpleWeather({
    location: 'New York, New York',
    woeid: '',
    unit: 'f',
    success: function(weather) {
      currentTemp = weather.temp;
    },
    error: function(error) {
      currentTemp = 150;
    }
  });
  $('#degrees').text(currentTemp);

由于某种原因,变量 currentTemp 的值在 simpleWeather 函数中设置时,不会在该函数之外进行。我能做什么?

【问题讨论】:

  • $('#degrees').text(currentTemp);放到成功函数里面
  • simpleWeather 是异步的...您的调用 `$('#degrees').text(currentTemp);` 在success 方法运行之前运行。
  • 这是时间问题,而不是范围问题。

标签: javascript


【解决方案1】:

$('#degrees').text(currentTemp) 不会等待 $.simplerWeather 启动 success 处理程序。您应该将在$.simplerWeather 之后执行所需的任何代码移动到success 处理程序(回调)

var currentTemp = 0;
  $.simpleWeather({
    location: 'New York, New York',
    woeid: '',
    unit: 'f',
    success: function(weather) {
      currentTemp = weather.temp;
      $('#degrees').text(currentTemp); 
    },
    error: function(error) {
      currentTemp = 150;
    }
  });

【讨论】:

    猜你喜欢
    • 2021-12-04
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 2010-12-07
    相关资源
    最近更新 更多