获取“i”的值来自 GEvent
我试图在按下地图上的每个图标时添加一个事件侦听器。我将信息存储在数据库中,我想要检索的值是“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'm trying to add an event listener to each icon on the map when it's pressed. I'm storing the information in the database and the value that I'm wanting to retrive is "i" however when I output "i", I get it's last value which is 5 (there are 6 objects being drawn onto the map)
Below is the code, what would be the best way to get the value of i, and not the object itself.
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);
});
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您遇到了关闭问题。您的函数会看到
i
的最后一个值。只需添加另一个闭包即可修复您的错误:You have an issue with closures. Your functions see
i
's last valuse. Simply add another closure to fix your error: