0

I am trying to create an object in a for loop , and add a click function in the loop which can call another function and pass in the index - so that I know which object it was that was clicked. Here is the loop:

        var markers = [];
        for (x = 0; x < response.data.length; x++) {
            var ret = {
                onClicked: function () { onMarkerClicked(x); },
                locationId: response.data[x].CASO_nid,
                id: x,  //-shows proper index
                latitude: response.data[x].Latitude,
                longitude: response.data[x].Longitude,
                title: x,  // shows proper index
                showWindow: false,
                fit: true
            };
            markers.push(ret);

        }
        $scope.results = markers;

now when I look at the objects created in the console I see that every place that I added the x got set correctly , except in that click function , there is is just x. The problem is that when I click this object after it is created then they all have x as the last number that it was set to. How can I write this function to properly get the ndex , and not just the final number??

 see in console:


 0:  
Objectfit:
trueid: 0 
idKey: 0 
latitude: 42.0230636
locationId:10299 
longitude: -87.9620276
 onClicked: function () { onMarkerClicked(x); }
 showWindow: false
 title: 0
4

1 回答 1

2

尝试为每个循环创建闭包:

for (index = 0; index < response.data.length; index++) {
     (function(x) {
            var ret = {
                onClicked: function () { onMarkerClicked(x); },
                locationId: response.data[x].CASO_nid,
                id: x,  //-shows proper index
                latitude: response.data[x].Latitude,
                longitude: response.data[x].Longitude,
                title: x,  // shows proper index
                showWindow: false,
                fit: true
            };
            markers.push(ret);
      }(index))
 }

另一个使用forEach的解决方案,因为这也会创建闭包。

response.data.forEach(function (value, x){
    var ret = {
                onClicked: function () { onMarkerClicked(x); },
                locationId: value.CASO_nid,
                id: x,  //-shows proper index
                latitude: value.Latitude,
                longitude: value.Longitude,
                title: x,  // shows proper index
                showWindow: false,
                fit: true
            };
        markers.push(ret);
});
于 2014-10-12T05:18:18.923 回答