Frage

Ich versuche, einen Ereignis-Listener zu jedem Symbol auf der Karte hinzufügen, wenn sie gedrückt wird. Ich bin in der Datenbank, die Informationen zu speichern und den Wert, den ich retrive bin zu wollen ist „i“ aber wenn ich Ausgabe „i“, bekomme ich es letzte Wert ist, der 5 ist (es gibt 6 Objekte auf der Karte gezogen wird)

Im Folgenden finden Sie den Code ein, was der beste Weg wäre, den Wert von i zu erhalten, und nicht das Objekt selbst.

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);
            });
        }
    });
War es hilfreich?

Lösung

Sie haben ein Problem mit Schließungen. Ihre Funktionen sehen i letzten Wert. Einfach einen anderen Verschluss fügen Sie Ihre Fehler zu beheben:

for(var i=0; i<lotLoc.length; i++) {
    (function(i){
        // ...
    })(i); //run the function with i as argument
}//for
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top