0

我有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,如果有差別:

+0

你什麼時候打電話給'foo'? –

+0

另外,當我放置調試警報時,似乎在調用bar()之前創建'myVar'。 –

+0

foo()被調用onClick按鈕(在HTML中的隱藏變量之前) –

回答

1

bar異步運行,因爲geocoder一樣。這意味着,

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

實際執行

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

不能阿賈克斯用這種方式。所有依賴於results/status的工作都必須在回調中完成。

+0

謝謝。我最終做的只是將bar()放入foo()中,而不是將其作爲附加函數。我本來希望有單獨的功能,但我可能不需要它。 –

+0

@AdamMThompson請注意並接受有用的答案 –

1

jsfiddle Demo

運行正常我。確保在定義前定義函數以實際使用function

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

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

foo();