我的 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/