如何在jquery函数中传递变量
How to pass a variable inside a function inside a jquery function?
所以我正在使用谷歌地图api。我必须在对象内部插入值lat和lon,但我不能这样做:
$.get(url).done(buscaGPS(data, i));
function buscaGPS(data, i) {
}
代码objecto = [{
"address_1": "Avenida da Republica, 15A",
"city": "Lisbon",
"country": "pt",
"id": 1534282,
"name": "Pastelaria Versailles"
}, {
"address_1": "Avenida da Republica, 15A",
"city": "Lisbon",
"country": "pt",
"id": 1534282,
"name": "Pastelaria Versailles"
}];
for (var i = 0; i < objecto.length; i++) {
var url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + objecto[i].address_1 + "+" + objecto[i].city + "+" + objecto[i].country + "&sensor=false";
$.get(url).done(buscaGPS);
};
function buscaGPS(data) {
objecto[i].lat = data.results[0].geometry.location.lat;
objecto[i].lon = data.results[0].geometry.location.lng;
}
听起来你的意思是你想做…
// create a closure to capture the index
function callback(index){
return function(data) {
objecto[index].lat = data.results[0].geometry.location.lat;
objecto[index].lon = data.results[0].geometry.location.lng;
}
}
for (var i = 0; i < objecto.length; i++) {
var url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + objecto[i].address_1 + "+" + objecto[i].city + "+" + objecto[i].country + "&sensor=false";
$.get(url).done(callback(i));
}
虽然Shanimal的解决方案非常合理,但是它使用function-return -a-function给代码增加了一些复杂性。你实际上不需要那样来获得闭包;一个简单的函数调用就可以了。
考虑以下选项:
for( var i = 0; i < objecto.length; i++ ) {
geocode( objecto[i] );
}
function geocode( place ) {
var url =
"http://maps.googleapis.com/maps/api/geocode/json?address=" +
place.address_1 + "+" + place.city + "+" + place.country +
"&sensor=false";
$.get(url).done( function( data ) {
var location = data.results[0].geometry.location;
place.lat = location.lat;
place.lon = location.lng;
});
}
注意,这也去掉了所有的objecto[i]
和objecto[index]
引用,使用一个简单的place
变量来替换它们。
我发现这种方法比一个返回一个函数的函数更容易理解。
与地理编码相关的其他评论:您的objecto
数组中是否有更多的位置?如果多于几个,则需要减慢地理编码请求的速度,而不是连续触发它们。
此外,如果这些是固定的位置,您应该对它们进行一次地理编码,并将lat/long存储在数组中,这样您就不必在浏览器中对它们进行地理编码。这将使您的地图加载速度更快,并避免地理编码多个地址的问题。
相关文章:
- 带有两个变量函数的Ajax提交表单
- 设置变量函数不起作用
- 为什么使用 ||在变量函数声明中
- Javascript 变量函数不保留值
- 为什么要在函数定义之外引用静态变量(函数属性)
- jQuery 变量函数无法运行
- 循环中的变量函数定义
- javascript onclick设置为变量函数名
- JavaScript:调用已启动类(数据包处理程序)的变量函数
- Javascript测试存根全局变量函数
- Aptana能否识别其他文件中定义的变量/函数
- jquery将其传递给变量函数
- 传递一个变量函数到数组[Javascript]
- 如何使用' this '像一个对象,并通过字符串获得它的变量/函数
- javascript变量/函数的首字母是什么意思?
- Javascript .apply带有变量函数名
- 在JavaScript中添加一个全局变量/函数(特别是NativeScript)
- 变量函数未定义错误
- AngularJS-继续检查变量/函数
- Javascript从本地向全局变量函数添加行