繁体   English   中英

执行函数完成后调用Javascript函数

[英]Javascript function calling after the executing function finishes

我正在使用Google Maps API。 我不知道为什么在index ++之后调用下面的函数。 据我所知,应该首先调用ReverseGeocode()。 取而代之的是,它是先递增然后调用该函数,这给我带来了麻烦。 警报框在编写时显示,但是在执行函数的最后一行(即(index ++))之后调用中间函数。

      function placeMarker(location)
      {
          alert("iiii");
          ReverseGeocode(location.lat(),location.lng());
          alert("jjjk");
          index++;
      }

这是我的ReverseGeoCode

  function ReverseGeocode(lat,lng) {     
     var latlng = new google.maps.LatLng(lat, lng);
     geocoder.geocode({'latLng': latlng}, function(results, status)
  {
      if (status == google.maps.GeocoderStatus.OK) 
     {
           if (results[1])
      {

          places[index]=results[0].formatted_address;
          alert(places[index]+"index="+index);
          AddRow('table',results[0].formatted_address);
          document.getElementById("dataa").innerHTML+=results[0].formatted_address+"<br/>";
      }
  }
  else 
  {
    alert("Geocoder failed due to: " + status);
      }
    });
  }

请解释。 提前致谢。

警报位于您的回调函数内部,该回调函数将在geocoder.geocode完成计算后执行。

geocoder.geocode似乎是异步的。 通常,这意味着geocoder.geocode将开始在其他地方进行工作,而您的程序将继续其本地结论。 geocoder.geocode稍后完成时,它将执行您提供的回调函数。

我认为geocoder.geocode是异步的。 index的值增加时,它将稍后执行您的匿名函数。

function placeMarker(location)
 {
 alert("iiii")
 ReverseGeocode(location.lat(),location.lng(),index);
 alert("jjjk");
 index++;

}

function ReverseGeocode(lat,lng,index) {     
     var latlng = new google.maps.LatLng(lat, lng);
     geocoder.geocode({'latLng': latlng}, function(results, status)
  {
      if (status == google.maps.GeocoderStatus.OK) 
     {
           if (results[1])
      {

          places[index]=results[0].formatted_address;
          alert(places[index]+"index="+index);
          AddRow('table',results[0].formatted_address);
          document.getElementById("dataa").innerHTML+=results[0].formatted_address+"<br/>";
      }
  }
  else 
  {
    alert("Geocoder failed due to: " + status);
      }
    });
  }

在这种情况下, index将进入匿名函数的本地范围,因此不会被覆盖。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM