admin管理员组文章数量:1390905
I have a bunch of markers and wish to add a mouseover handler to each of them. I am looping through my coordinates, creating new markers and then adding a handler. In the handler I wish for it to modify the DOM element with a specific id.
The problem is, even though in the loop the id is changing through each iteration, the actual handler applied all use the last postId generated.
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);
});
}
}
The problem is that no matter which marker I hover over, postId is being printed out as "1".
However when I am going through the loop, the postId is different each time.
Console output:
21
20
12
10
9
3
2
1
However, when I hover over the markers it always says 1.
I have a bunch of markers and wish to add a mouseover handler to each of them. I am looping through my coordinates, creating new markers and then adding a handler. In the handler I wish for it to modify the DOM element with a specific id.
The problem is, even though in the loop the id is changing through each iteration, the actual handler applied all use the last postId generated.
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);
});
}
}
The problem is that no matter which marker I hover over, postId is being printed out as "1".
However when I am going through the loop, the postId is different each time.
Console output:
21
20
12
10
9
3
2
1
However, when I hover over the markers it always says 1.
Share Improve this question asked May 30, 2011 at 22:34 Razor StormRazor Storm 12.3k20 gold badges95 silver badges151 bronze badges 1- Does alert(postID) in the event have the same issue? – Oliver Commented May 30, 2011 at 22:54
1 Answer
Reset to default 7That's because you create one global postId
that all listeners share. You can create private versions like so:
(function () {
var postId=results[i][1];
google.maps.event.addListener(markers[markers.length-1], 'mouseover', function() {
console.log(postId);
});
})();
本文标签: javascriptadding marker listener in a loop in google maps api v3Stack Overflow
版权声明:本文标题:javascript - adding marker listener in a loop in google maps api v3? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744605435a2615325.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论