2016-09-26 41 views
0

我有这个问题与jQuery。我的jQuery中的一些函数返回“未捕获的ReferenceError:curLocZip未定义”当我在另一个函数中调用它时。我有这个问题与jquery与一个功能没有定义的指示,同时我定义的功能

下面是函数的定义:

function curLocZip(){ 
     curZipCode = ""; 
     if (navigator.geolocation) { //Checks if browser supports geolocation 
      navigator.geolocation.watchPosition(function (position) { 
       var geocoder = new google.maps.Geocoder(); 

       var lat = position.coords.latitude; 
       var lng = position.coords.longitude; 
       var latlng = new google.maps.LatLng(lat, lng) 

       geocoder.geocode({'latLng': latlng}, function(results, status) { 
        if (status == google.maps.GeocoderStatus.OK) { 
         if (results[0]) { 
          for (i = 0; i < results[0].address_components.length; i++) { 
           if (results[0].address_components[i].types[0] == 'postal_code'){ 
            curZipCode = results[0].address_components[i].short_name; 
            break; 
           } 
          } 
         } 
        } else { 
         console.log("Geocoder failed due to: " + status); 
        } 
       });    
      }); 
     } else { 
      alert("Geolocation is not supported by this browser."); 
     } 
} 

我叫它在另一个功能,像这样:

curLocZip(); 

我不知道为什么我收到表示错误curLocZip () 没有定义。

+2

代码中的“curLocZip”定义在哪里?它在哪里被称为? – Joseph

+0

a)您何时以及何时定义了功能b)何时何地称呼它? – Danmoreng

+0

我在'$(document).ready(function(){...})中定义了_curloczip()_(fna curLocZip);'和我用相同的方法调用了它。通过在_curloczip()_中为全局变量设置一个默认值,然后调用该函数,我注意到该函数在调用时实际返回一个值,只是在API处理完成之前返回该值。我现在正在寻找如何在函数返回被调用之前完成API处理。 –

回答

-1

您可能正在页面加载中定义它并在定义它之前调用它。您必须在呼叫加载后才能使呼叫发挥作用,因此您可能需要在onLoad回拨上开始处理。

+0

函数调用似乎工作得很好,我已经注意到在控制台中打印出来之后。这个问题似乎是在API处理完成之前函数返回的。因此,当我删除Google Maps API调用并仅返回一个带有设置数据的变量时,函数调用似乎可以正常工作。像这样:'function curloczip(){ \t \t curZipCode =“38104”; \t \t return curZipCode; }' –