문제

눌렀을 때 맵에서 각 아이콘에 이벤트 리스너를 추가하려고합니다. 데이터베이스에 정보를 저장하고 있으며 검색하려는 값은 "I"이지만 "I"를 출력 할 때 5 인 마지막 값을 얻습니다 (맵에 그려진 6 개의 개체가 있습니다).

아래는 코드입니다. 객체 자체가 아니라 i의 값을 얻는 가장 좋은 방법은 무엇입니까?

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);
            });
        }
    });
도움이 되었습니까?

해결책

폐쇄에 문제가 있습니다. 당신의 기능은 본다 i마지막 valuse. 오류를 해결하기 위해 다른 폐쇄를 추가하기 만하면됩니다.

for(var i=0; i<lotLoc.length; i++) {
    (function(i){
        // ...
    })(i); //run the function with i as argument
}//for
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top