javascript - js 在一个函数内如何调用另一个函数的变量
怪我咯
怪我咯 2017-04-11 13:01:10
[JavaScript讨论组]

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

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值

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(3)
怪我咯
/* 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);    
    });
}
黄舟

yourCurCity声明在外部或者在getJSON成功后调用getWeather时传参。如果getWheather不是异步的话。只能采用后者,或者是进行promise回调。

PHP中文网

异步获取的需要用回调函数 推荐 Promise 写法 避免回调金字塔

showPosition(){
    return 
    $.getJSON(url)
    .then(getWeather);
}

getWeather(data){
    console.info(data.city);
};
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号