谷歌地图-不知道为什么我总是得到第一个信息窗口
Google maps - not sure why I am always getting the first infowindow
我有以下代码,每次单击其中一个标记,我都会得到第一个信息窗口。我有181个信息窗口和181个标记。感谢您的帮助。
var i=0;
$.each(in_locations,function(k,v){
console.log(v);
var marker_latlng = new google.maps.LatLng(v.latitude, v.longitude);
markers[i] = new google.maps.Marker({
position: marker_latlng,
map: map,
title:"here is my title" + v.id
});
infowindows[i] = new google.maps.InfoWindow({
content: "here is some content string" + v.id,
});
google.maps.event.addListener(markers[i], 'click', function() {
alert('number of infowindows: ' + infowindows.length + ' and value is: ' + i);
infowindows[i].open(map,markers[i]);
});
i++;
});
thx
警报是否告诉您值始终为181?您需要将处理程序声明包装在一个闭包中,以使用i
的外部值来停止它(一旦循环完成,它将始终为181)
(function(i){
google.maps.event.addListener(markers[i], 'click', function() {
alert('number of infowindows: ' + infowindows.length + ' and value is: ' + i);
infowindows[i].open(map,markers[i]);
});
}(i));
编辑:因为你使用的是jQuery的$.each函数,它为每个迭代提供了自己的范围(因为每个迭代都在调用一个函数),所以你也可以通过创建一个局部变量来解决这个问题,比如j,它获取i的外部值。
var j = i;
google.maps.event.addListener(markers[i], 'click', function() {
alert('number of infowindows: ' + infowindows.length + ' and value is: ' + j);
infowindows[j].open(map,markers[j]);
});
(这是因为每次迭代都会创建一个新的j
,而之前只有1个i
,因为您在迭代函数之外声明了它。)
更新
- 演示:http://jsbin.com/obunap/5
$.each(in_locations, function(i, item){
console.log(i);
var marker_latlng = new google.maps.LatLng(item.latitude, item.longitude);
var markers = new google.maps.Marker({
position: marker_latlng,
map: map,
title:"here is my title" + item.id
});
var infowindows = new google.maps.InfoWindow({
content: "here is some content string" + item.id,
});
google.maps.event.addListener(markers, 'click', function() {
alert('number of infowindows: ' + in_locations.length + ' and value is: ' + i);
infowindows.open(map, markers);
});
});
- 解释您已经处于循环
$.each
中,因此不需要增加i++
迭代器
相关文章:
- 使用数据上的角度更改设置集合的第一个元素的动画
- 当单击第一个李时,它显示内容一,当单击第二个李时,它显示内容二
- 字母计数:返回重复字母数最多的第一个单词
- 如何使用Javascript在HTML表中查找第一个空行
- 分页:如何用AJAX加载第一个页面
- 全局标志仅与第一个匹配项匹配的Regexp
- 访问ng repeat中的第一个项目
- 使用jQuery只返回选中复选框后的第一个表单元格值
- 使用jQuery插入HTML页面的第一个项目缺少结束标记
- 关闭第二个事件源上的第一个事件源's onopen方法
- 无法获取vis.js最后一个或第一个选定的网络节点
- 如何设置第一个手风琴面板关闭
- 使用filter和map方法将数组中某些元素的第一个字母大写-JavaScript
- jQuery空选择,但不是第一个选项
- JavaScript Regex 将单词替换为其第一个字母,除非在括号内
- ng-repeat图像上的指令仅提取有关第一个图像的信息
- 谷歌地图-不知道为什么我总是得到第一个信息窗口
- 使用AngularJS grag$在ng中的第一个项目重复,并使用它在页面上以其他形式打开项目信息
- 单击列表中的项目->查看详细信息但没有输出?Firebase.child失败:第一个参数是无效路径
- 当第二个信息窗口出现时,关闭第一个信息窗口