jQuery从函数中检索值

时间:2013-10-19 23:36:27

标签: jquery

我有一个非常基本的功能,可以抓住用户的当前位置。当我提醒或记录geoCoder变量时,我成功获得了一个值。我试图将geoCoder值放在我的JSON调用中。

function userLocation(location, callback) {
    var geoCoder = new google.maps.Geocoder();
        geoCoder.geocode({
            location: location
        }
    console.log(geoCoder);
}

var jsonCall;
jsonCall = '/bin/userlocation/locations.' + geoCoder + '.json'

当我运行这个时,我得到一个 geoCoder没有定义js错误。我如何获取geoCoder变量的值?我是一个新手,所以感谢代码示例。

2 个答案:

答案 0 :(得分:1)

var jsonCall; //declaring outside and before a function means the var will be accessible inside and outside of the function

function userLocation(location, callback) {
    var geoCoder = new google.maps.Geocoder();
        geoCoder.geocode({
            location: location
        }
    console.log(geoCoder);
    jsonCall = '/bin/userlocation/locations.' + geoCoder + '.json'
}

console.log(jsonCall);

答案 1 :(得分:0)

您正在创建函数中的变量并尝试达到函数范围之外。尝试从函数中定义它并在任何地方分配值。

定义为var geoCoder;超出功能。 并填写geoCoder的功能。

var geoCoder;
function blabla(){
geocoder = dosomething
}

console.log(geoCoder); // this returns null
blabla();
console.log(geoCoder); // now u can see it is not empty