【发布时间】:2013-04-01 22:56:52
【问题描述】:
我有类似于以下的 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,如果这有影响的话:
【问题讨论】:
-
什么时候打电话给
foo? -
另外,当我放置调试警报时,似乎在调用 bar() 之前创建了“myVar”。
-
foo() 在按钮上被调用(在 HTML 中的隐藏变量之前)
-
您何时尝试访问
myVar? -
尝试访问 myVar(或至少是放入隐藏变量 'coords' 中的值)在 foo() 中的几行
标签: javascript function google-maps-api-3 pass-by-reference hidden-variables