javascript - 在函数内的函数中分配隐藏变量

标签 javascript function google-maps-api-3 pass-by-reference hidden-variables

我的 JavaScript 代码类似于以下内容,但是当我尝试在 foo() 中使用“myVar”时,其值未定义。我还尝试将变量传递到 bar() 并直接分配它,但不会通过引用传递。

function foo() { 
   bar();
   var myVar = document.getElementById('coords').value;
   // myVar should now be (40.7143528, -74.0059731)
   alert(myVar); // returns blank

   var request = {
    location: myVar,
    radius: 500,
    types: [type] //previously defined 
   };

   //Then send a search request to Google...
}

function bar() {
   geocoder.geocode( {'address':address}, function(results, status) {

      document.getElementById('coords').value = results[0].geometry.location;
      // Let's say the location is NYC (40.7143528, -74.0059731)

     alert(document.getElementById('coords').value); //returns the correct value
     // however, this pops up after the pop up in function foo() 

   });
}

使用以下 HTML

<input type="hidden" id="coords" name="coords"/>

真正的代码是使用 Google Maps API(如果这有区别的话):

最佳答案

bar 异步运行,因为 geocoder 异步运行。这意味着

document.getElementById('coords').value = results[0].geometry.location;

实际执行之后

var myVar = document.getElementById('coords').value;

你不能这样使用ajax。所有依赖结果/状态的工作都必须在回调中完成。

关于javascript - 在函数内的函数中分配隐藏变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15753342/

相关文章:

javascript - JQuery datepicker() 通过 ASP.net 中的 CSS 类动态创建的 TemplateFields

python - 需要编写一个函数来接收颜色列表,并输出它们的负颜色(来自字典的对)

c++ - 如何访问 std::array 给定其在 C++ 中的指针的元素

javascript - 函数中的变量范围

javascript - 如何使用 Html5 地理定位链接到 google map 打印方向?

android - 如何在 setOnInfoWindowClickListener 中获取在 Google Map 中单击的标记的 ID

javascript - 不使用 JavaScript/jQuery 选中/取消选中复选框

javascript - 自动滚动 DIV -

javascript - Webview不加载javascript获取内容