我有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,如果有差別:
你什麼時候打電話給'foo'? –
另外,當我放置調試警報時,似乎在調用bar()之前創建'myVar'。 –
foo()被調用onClick按鈕(在HTML中的隱藏變量之前) –