可能重复:
Javascript closure inside loops - simple practical example
Please explain the use of JavaScript closures in loops
for (var i = 0; i < pois.length; i++) {
pois[i].marker.addEventListener('dblclick', function (data) {
var infoWindow = new BMap.InfoWindow(pois[i].address, opts);
map.openInfoWindow(infoWindow, map.getCenter());
})
}
这是我的代码。
显然这里有一个错误
new BMap.InfoWindow(pois [i] .address,opts);
如何在pois [i] .marker监听器功能中使用pois [i] .address?
答案 0 :(得分:2)
for (var i = 0; i < pois.length; i++) {
setupEventListener(pois[i]);
}
function setupEventListener(obj) {
var address = pois[i].address;
obj.marker.addEventListener('dblclick', function (data) {
var infoWindow = new BMap.InfoWindow(address, opts);
map.openInfoWindow(infoWindow, map.getCenter());
});
}