2009-11-02 179 views
10

我的代碼傳遞參數給回調函數

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

} 

如何解決這個問題?

回答

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

這將記錄09,根據需要,由於with引入一個新的範圍。

JavaScript 1.7有一個更好的let聲明,但在廣泛支持之前,您可以使用with

並使用var作爲變量。

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