Pass parameter to callback function

前端 未结 4 1887
有刺的猬
有刺的猬 2021-02-20 16:35

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 c         


        
相关标签:
4条回答
  • 2021-02-20 16:42

    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));     
    
    0 讨论(0)
  • 2021-02-20 16:48

    Looks like you've got a closure problem. See these questions:

    • google maps api all markers opening the same infowindow
    • google maps trouble closures passing by reference
    • dynamically adding listeners to google maps markers
    0 讨论(0)
  • 2021-02-20 16:52

    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);
        }
    }
    
    0 讨论(0)
  • 2021-02-20 17:00

    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.

    0 讨论(0)
提交回复
热议问题