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();