在函数内的函数中赋值隐藏变量
Assigning hidden variable in a function within a function
我有类似于下面的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,如果这有区别:
bar
异步运行,因为geocoder
异步运行。这意味着
document.getElementById('coords').value = results[0].geometry.location;
实际上在
之后执行var myVar = document.getElementById('coords').value;
你不能这样使用ajax。所有依赖于results
/status
的工作都必须在回调中完成。
jsfiddle演示
对我来说运行良好。在定义函数时,请确保在定义前实际使用function
。
function foo() {
bar();
var myVar = document.getElementById('coords').value;
}
function bar() {
document.getElementById('coords').value = 4;
}
foo();
相关文章:
- 从var向代码隐藏函数传递值
- javascript函数和代码隐藏函数的执行顺序
- 在函数调用中封装数据除了隐藏数据之外还有什么优点
- 仅在第一个结果中显示/隐藏MySQL结果函数
- ASP.net Javascript函数中的隐藏字段为null
- 使用Javascript的多显示隐藏函数
- 如何分解jQuery"toggle”;函数转换为separate“;显示“;以及“;隐藏“;功能
- 使用javascript函数检索隐藏的文本值时出现对象HTMLinputElement错误
- jQuery隐藏函数与“;按钮“;以及“;span”;但不是用“;a“;要素
- jQuery隐藏函数出现问题
- 为什么需要从代码隐藏调用 JavaScript 函数
- 在 JavaScript 中,当我们实例化派生对象时,原型的函数隐藏在哪里
- MVC ASP.Net Javascript - 如果 Url 没有 id,如何使用 javascript 函数隐藏按钮
- 函数隐藏在javascript中
- jquery.hide()函数-隐藏手机,显示桌面
- 当用标签形式覆盖时,为什么函数隐藏/显示元素不起作用
- 我无法用我的函数隐藏jquery自动完成
- 使用onclick函数隐藏父元素
- JS函数隐藏元素值
- JQuery动态函数隐藏元素