将参数传递给回调函数 [英] Pass parameter to callback function
问题描述
我的代码
//执行ajax请求并获取JSON响应
for(var i = 0; i< data.results.length; i ++){
result = data.results [i];
//做东西并创建谷歌地图marker
marker = new google.maps.Marker({
position:new google.maps.LatLng(result.lat,result.lng),
map:map,
id:result.id
});
google.maps.event.addListener(marker,'click',function(){
createWindow(marker.id); //< ====这不起作用,因为标记总是指向到这个函数被称为
}时的最后结果);;
}
如何解决这个问题? b
试试这个:
with({mark:标记}){
google.maps.event.addListener(mark,'click',function(){
createWindow(mark.id);
});
$ / code>
一个例子演示了如何使用 以上将记录 code $:
$ b $ pre $ for(var i = 0; i <10; i ++){
setTimeout (function(){console.log(i);},1000);
$ / code> 10 $ c $对于(var i = 0; i <10; i ++){
with(),
{foo:i}){
setTimeout(function(){console.log(foo);},1000);
$ b $ p $这将记录 0
到 9
,这要感谢和
引入一个新的范围。
JavaScript 1.7有一个更好的 let
语句,但在广泛支持之前,您可以使用与
。
并使用 var
作为您的变量。
my code
// do ajax request and get JSON response
for (var i = 0; i < data.results.length; i++) {
result = data.results[i];
// do stuff and create google maps marker
marker = new google.maps.Marker({
position: new google.maps.LatLng(result.lat, result.lng),
map: map,
id: result.id
});
google.maps.event.addListener(marker, 'click', function() {
createWindow(marker.id); //<==== this doesn't work because marker always points to the last results when this function is called
});
}
How to solve this?
Try this:
with ({ mark: marker }) {
google.maps.event.addListener(mark, 'click', function() {
createWindow(mark.id);
});
}
An example that demonstrates the use of with
:
for (var i = 0; i < 10; i++) {
setTimeout(function() { console.log(i); }, 1000);
}
The above will log 10
ten times.
for (var i = 0; i < 10; i++) {
with ({ foo: i }) {
setTimeout(function() { console.log(foo); }, 1000);
}
}
This will log 0
to 9
, as desired, thanks to with
introducing a new scope.
JavaScript 1.7 has a let
statement that is nicer, but until that is widely supported, you can use with
.
And use var
for your variables.
这篇关于将参数传递给回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!