简体   繁体   English

将参数传递给回调函数

[英]Pass parameter to callback function

My code 我的代码

// do ajax request and get JSON response //执行ajax请求并获取JSON响应

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 : 演示使用with的示例:

for (var i = 0; i < 10; i++) {
    setTimeout(function() { console.log(i); }, 1000);
}

The above will log 10 ten times. 以上将记录10次。

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. 这将记录09 ,如需要的话,由于with引入一个新的范围。

JavaScript 1.7 has a let statement that is nicer, but until that is widely supported, you can use with . JavaScript 1.7中有一个let语句是更好的,但是直到,获得广泛支持,您可以使用with

And use var for your variables. 并使用var作为变量。

The classic closure problem strikes again! 经典的关闭问题再次出现!

  google.maps.event.addListener(marker, 'click', function(id) {
    return function(){
      createWindow(id); //<==== this doesn't work because marker always points to the last results when this function is called
    }
  }(marker.id));     

try this one 试试这个

var marker = new Array();
for (var i = 0; i < data.results.length; i++) {  
    result = data.results[i];
    // do stuff and create google maps marker    
    marker[i] = new google.maps.Marker({  
        position: new google.maps.LatLng(result.lat, result.lng),   
        map: map,  
        id: result.id  
    });  
    google.maps.event.addListener(marker[i], 'click', example(marker[i].id));  

}

create new function 创造新的功能

function example(my_window){
    return function(){
        createWindow(my_window);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM