将变量从回调函数传递给另一个函数?

时间:2014-04-30 21:26:39

标签: javascript jquery function variables

我正在设置HTML5 GeoLocation脚本,我想将邮政编码存储在cookie中,但现在我只想弄清楚如何将邮政编码变量传递给另一个函数。

以下是基于lat / long反转地理代码的脚本:

function retrieve_zip(callback)
{
    try { if(!google) { google = 0; } } catch(err) { google = 0; } // Stupid Exceptions
    if(navigator.geolocation) // FireFox/HTML5 GeoLocation
    {
        navigator.geolocation.getCurrentPosition(function(position)
        {
            zip_from_latlng(position.coords.latitude,position.coords.longitude,callback);
        });
    }
    else if(google && google.gears) // Google Gears GeoLocation
    {
        var geloc = google.gears.factory.create('beta.geolocation');
        geloc.getPermission();
        geloc.getCurrentPosition(function(position)
        {
            zip_from_latlng(position.latitude,position.longitude,callback);
        },function(err){});
    }
}
function zip_from_latlng(latitude,longitude,callback)
{
    // Setup the Script using Geonames.org's WebService
        var script = document.createElement("script");
        script.src = "http://ws.geonames.org/findNearbyPostalCodesJSON?lat=" + latitude + "&lng=" + longitude + "&callback=" + callback;
        console.log(script.src);
    // Run the Script
        document.getElementsByTagName("head")[0].appendChild(script);
}
function callback(json)
{
    zip = json.postalCodes[0].postalCode;
    country = json.postalCodes[0].countryCode;
    state = json.postalCodes[0].adminName1;
    county = json.postalCodes[0].adminName2;
    place = json.postalCodes[0].placeName;
    alert(zip);
}
$('#findLocation').click(function(event) {
    event.preventDefault();
    console.log(zip); // This is giving me undefined currently
});

所以基本上,在回调函数中,我想将邮政编码存储为变量(而不是在警报中显示),然后在底部的on click函数中,我希望能够显示存储在上一个回调函数中的邮政编码。

任何帮助都非常感谢,对Javscript / jQuery来说还是新手,谢谢!

3 个答案:

答案 0 :(得分:1)

在代码开头定义var zip。你还没定义它。

我没有尝试,但它应该可以解决你的问题。


此外,您似乎忘记在callback函数中定义其他变量。

答案 1 :(得分:1)

您可以将zip设置为全球'通过将它包含在文档顶部的函数之外来变量,如下所示:

var zip;
...

或者,您可以考虑在全局'中定义一个对象。 level并将其用作命名空间来存储变量,如:

window.address = {};

function callback(json){
    address.zip = json.postalCodes[0].postalCode;
    address.country = json.postalCodes[0].countryCode;
    address.state = json.postalCodes[0].adminName1;
    address.county = json.postalCodes[0].adminName2;
    address.place = json.postalCodes[0].placeName;
}

$('#findLocation').click(function(event) {
    event.preventDefault();

    console.log(address.address);
    console.log(address.zip);
    ...
});

我希望这有帮助!

答案 2 :(得分:0)

我要做的是避免事件处理程序中的匿名函数,即创建一个新的命名函数 - 它在调试期间为您提供了可追溯性的附加好处 - 然后将该函数用作事件处理程序回调:

function eventHandlerFunction(event) {
  var zip;
  event.preventDefault();

  zip = eventHandlerFunction.zip;
  console.log(zip);
}

function callback(json) {
  var zip;
  zip = doSomethingWithJsonToGetTheZip();
  eventHandlerFunction.zip = zip;
}

$("#findLocation").click(eventHandlerFunction);

或者,更好的是,将其编码为模块然后您具有成员封装,您可以在函数之间共享变量而无需修改全局对象。您永远不知道另一个库何时会修改您正在使用的同一个全局成员。

   var yourModule = (function($) {
      var zip;

      function retrieveZip(callback) {
        // your code
      }

      function callback(json) {
        // do something with json
        zip = json.zip; // or whatever
      }

      $("#findLocation").click(function(event) {
         event.preventDefault();
         console.log(zip);  // zip is visible in the parent scope + this scope
      });
   }(jQuery));
相关问题