[英]adding marker listener in a loop in google maps api v3?
我有一堆標記,並希望為每個標記添加一個鼠標懸停處理程序。 我正在遍歷我的坐標,創建新標記,然后添加一個處理程序。 在處理程序中,我希望它修改具有特定 id 的 DOM 元素。
問題是,即使在循環中 id 在每次迭代中都在變化,實際應用的處理程序都使用最后生成的 postId。
for(i in results)
{
r=results[i][0];
var postId=results[i][1]; // Different for each i
if (status == google.maps.GeocoderStatus.OK)
{
markers.push(new google.maps.Marker({
map: map,
position: r[0].geometry.location
}));
console.log(postId);
google.maps.event.addListener(markers[markers.length-1], 'mouseover', function() {
console.log(postId);
});
}
}
問題是,無論我 hover 超過哪個標記,postId 都被打印為“1”。
但是,當我通過循環時,postId 每次都不同。
控制台 output:
21
20
12
10
9
3
2
1
但是,當我在標記上 hover 時,它總是顯示 1。
那是因為您創建了一個所有聽眾共享的全局postId
。 您可以像這樣創建私有版本:
(function () {
var postId=results[i][1];
google.maps.event.addListener(markers[markers.length-1], 'mouseover', function() {
console.log(postId);
});
})();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.