Question

Je suis en train d'ajouter un écouteur d'événement à chaque icône sur la carte quand il est pressé. Je stocker les informations dans la base de données et la valeur que je suis désireux de retrive est « i » mais quand la sortie I « i », je reçois c'est la dernière valeur qui est 5 (il y a 6 objets en cours d'élaboration sur la carte)

Voici le code, ce qui serait la meilleure façon d'obtenir la valeur de i, et non l'objet lui-même.

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);
            });
        }
    });
Était-ce utile?

La solution

Vous avez un problème avec des fermetures. Vos fonctions voir la dernière valeur de i. Ajoutez simplement une autre fermeture pour corriger votre erreur:

for(var i=0; i<lotLoc.length; i++) {
    (function(i){
        // ...
    })(i); //run the function with i as argument
}//for
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top