将参数传递给回调函数

时间:2009-11-02 19:54:45

标签: javascript google-maps javascript-events

我的代码

//执行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
    });  

}

如何解决这个问题?

4 个答案:

答案 0 :(得分:24)

试试这个:

with ({ mark: marker }) {
    google.maps.event.addListener(mark, 'click', function() {  
        createWindow(mark.id);
    });
}

演示使用with

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

上述内容将记录10十次。

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

由于0引入了新范围,因此会根据需要将9记录到with

JavaScript 1.7有一个更好的let语句,但在广泛支持之前,您可以使用with

并使用var作为变量。

答案 1 :(得分:4)

classic closure problem再次罢工!

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

答案 2 :(得分:1)

答案 3 :(得分:1)

尝试这个

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

}

创建新功能

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