在函数内的函数中赋值隐藏变量

Assigning hidden variable in a function within a function

本文关键字:函数 隐藏 变量 赋值      更新时间:2023-09-26

我有类似于下面的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"/>

真正的代码是使用谷歌地图API,如果这有区别:

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

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

实际上在

之后执行
var myVar = document.getElementById('coords').value;

你不能这样使用ajax。所有依赖于results/status的工作都必须在回调中完成。

jsfiddle演示

对我来说运行良好。在定义函数时,请确保在定义前实际使用function

function foo() { 
 bar();
 var myVar = document.getElementById('coords').value;
}
function bar() {
 document.getElementById('coords').value = 4;
}
foo();