Domanda

Sto cercando di aggiungere un listener di eventi per ogni icona sulla mappa quando viene premuto. Sto memorizzare le informazioni nel database e il valore che sto volendo retrive è "Io", tuttavia quando l'uscita io "i", ho capito che è ultimo valore che è 5 (ci sono 6 oggetti in fase di elaborazione sulla mappa)

Di seguito è riportato il codice, quale sarebbe il modo migliore per ottenere il valore di i, e non l'oggetto stesso.

var drawLotLoc = function(id) {

    var lotLoc = new GIcon(G_DEFAULT_ICON);             // create icon object
    lotLoc.image = url+"images/markers/lotLocation.gif";     // set the icon image
    lotLoc.shadow = "";                                 // no shadow
    lotLoc.iconSize = new GSize(24, 24);                // set the size
    var markerOptions = { icon: lotLoc };               

    $.post(opts.postScript, {action: 'drawlotLoc', id: id}, function(data) {

        var markers = new Array();
        // lotLoc[x].description
        // lotLoc[x].lat
        // lotLoc[x].lng
        // lotLoc[x].nighbourhood
        // lotLoc[x].lot
        var lotLoc = $.evalJSON(data);

        for(var i=0; i<lotLoc.length; i++) {
            var spLat = parseFloat(lotLoc[i].lat);
            var spLng = parseFloat(lotLoc[i].lng);

            var latlng = new GLatLng(spLat, spLng)
            markers[i] = new GMarker(latlng, markerOptions);

            myMap.addOverlay(markers[i]);

            GEvent.addListener(markers[i], "click", function() {
                console.log(i);     // returning 5 in all cases. 
                                    // I _need_ this to be unique to the object being clicked.
                console.log(this);
            });
        }
    });
È stato utile?

Soluzione

Hai un problema con chiusure. Le funzioni vedono ultimo valore di i. Basta aggiungere un'altra chiusura per risolvere il tuo errore:

for(var i=0; i<lotLoc.length; i++) {
    (function(i){
        // ...
    })(i); //run the function with i as argument
}//for
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top