我有我相信類似的循環關係到關閉一個javascript問題:如何爲Bing Maps事件創建閉包?
How to copy a variable in JavaScript? JavaScript closure inside loops – simple practical example
我在冰繪製銷列表地圖和事件附加到每個以便爲每個引腳顯示信息框。每個引腳應該有一個不同的信息框。問題是,當事件觸發時,它始終顯示循環最後一次迭代的最後一個信息框,而不是與引發事件的引腳一起使用的信息框。下面是與循環結構的方法和我試圖建立一個封閉
monumentMap.plotData = function() {
monumentMap.theMap.entities.clear();
var monument = null
var loc = null;
for (var i = monumentMap.theData.length - 1; i >= 0; i--) {
monument = monumentMap.theData[i];
loc = new Microsoft.Maps.Location(monument.lat, monument.lon);
// construct a bing pushpin and add it to the item data
monument.pin = new Microsoft.Maps.Pushpin(loc, {
icon: 'http://media.maps101.com/' + monument.pinImg
});
// construct a bing infobox and add it to the item data
monument.infobox = new Microsoft.Maps.Infobox(loc, { // breakpoint 1
title: monument.title,
offset: new Microsoft.Maps.Point(-3, monument.pin.getHeight() - 5),
zIndex: 999,
visible: true
});
// add event listeners
// doesn't work
Microsoft.Maps.Events.addHandler(monument.pin, 'mouseover', function() {
return function(infobox) {
monumentMap.displayInfobox(infobox);
}(monument.infobox); // breakpoint 2: by the time this is executed monument.infobox is already "last not current"
});
// add the entities to the map view for this item
monumentMap.theMap.entities.push(monument.pin);
}
}
我無法讓我的頭周圍爲什麼它不工作。我在循環中設置了monument.infobox,如果我在標記爲「斷點1」的行上放置了一個斷點,我可以看到monument.infobox在每次循環迭代時都會改變,但是當我到達「斷點2」時直到事件觸發爲止),它會引用我創建的最後一個信息框,而不是附加事件處理程序時附加到該信息針的信息框。
到這點我半期待行monumentMap.theMap.entities.push(monument.pin);在循環中添加一堆最後一個引腳的副本,但它沒有。它的工作原理與每個循環迭代中不同的引腳一樣。
似乎已經做到了!我知道我以前嘗試過,它不起作用,但也許我忘了刷新瀏覽器頁面或其他東西。 – rushinge