الحصول على قيمة "أنا" من gevent
-
19-09-2019 - |
سؤال
أحاول إضافة مستمع حدث إلى كل أيقونة على الخريطة عند الضغط عليه. أقوم بتخزين المعلومات الموجودة في قاعدة البيانات والقيمة التي أرغب في استراحة "أنا" عندما أخرج "أنا"، أحصل على القيمة الأخيرة التي هي 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
التأجل الأخير. ما عليك سوى إضافة إغلاق آخر لإصلاح الخطأ الخاص بك:
for(var i=0; i<lotLoc.length; i++) {
(function(i){
// ...
})(i); //run the function with i as argument
}//for
لا تنتمي إلى StackOverflow