2009-11-02 4 views
10

mã của tôitham số Pass để gọi lại chức năng

// làm theo yêu cầu ajax và nhận được phản ứng 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 
    }); 

} 

Làm thế nào để giải quyết này?

Trả lời

24

Hãy thử điều này:

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

Một ví dụ chứng minh rằng việc sử dụng các with:

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

Ở trên sẽ ghi nhật ký 10 mười lần.

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

này sẽ đăng nhập 0-9, như mong muốn, nhờ with giới thiệu một phạm vi mới.

JavaScript 1.7 có tuyên bố let đẹp hơn, nhưng cho đến khi được hỗ trợ rộng rãi, bạn có thể sử dụng with.

Và sử dụng var cho các biến của bạn.

4

Cảnh cáo classic closure problem lần nữa!

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

thử này một

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

} 

tạo chức năng mới

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