javascript - js 在一个函数内如何调用另一个函数的变量

查看:314
本文介绍了javascript - js 在一个函数内如何调用另一个函数的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

有一个函数获取当前城市的值:

function getLoaction(){
                if (navigator.geolocation)
        {
        navigator.geolocation.getCurrentPosition(showPosition, showErr);
        }
        
  function showPosition(){
    $.getJSON(url,function(data){
        var yourCurCity = data.city;
    })
}

然后在另一个函数中调用yourCurCity的值

function getWeather(){

    console.log(yourCurCity);//显示为undefine
    $.ajax(url,{
    data:{"city":yourCurCity},function(data){
        ///....
    }
    
    })


}

在getWheather函数中怎样调用showPosition 的city值

解决方案

/* jQuery < 1.5 */    
function showPosition(){
  $.getJSON(url,function(data){
    var yourCurCity = data.city;

    getWeather(yourCurCity);//需要在这儿调用,并且需要把参数传过去。
  })
}
    
function getWeather(theCity){
  console.log(theCity);
  $.ajax({
    url,
    data: {"city":theCity},
    function(data) {
      ///....
    }
  });
}
    
/* jQuery >= 1.5 */    //1.5以后,ajax相关函数返回的对象成了一个推迟对象,可以用一些额外的函数。
function showPosition() {
  $.getJSON(url)
    .done(function(data) {
      var yourCurCity = data.city;

      getWeather(yourCurCity);
  })
    .fail(function(data) {
      console.log(data);    
  });
}
        
function getWeather(theCity) {
  console.log(theCity);
  $.ajax({
    url,
    data:{"city":theCity}
  })
    .done(function(data) {
    ///...
    })
    .fail(function(data) {
      console.log(data);    
    });
}

这篇关于javascript - js 在一个函数内如何调用另一个函数的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆