所以我有这个代码,循环遍历window.towns
中的每个城镇,这是一个按城镇名称的第一个字符排序的嵌套对象。像这样:
//sample data:
window.towns = {
'A' : {
"Aberdeen" : {
"town_info": {
"google_maps": {
"lat" : 47.561236,
"lng" : 0.1235467 }
}
} ,
"Agency Village" : {
"town_info": {
"google_maps": {
"lat" : 47.561236,
"lng" : 0.1235467 }
}
}
},
'B' : { //towns beginning with B
},
'C' : {},
// ... all the way thru 'Z'
}
我的代码然后循环遍历字母表中的每个字母,并且对于每个字母,循环遍历以该字母开头的城镇,在每个城镇的谷歌地图上创建标记,以及当您点击时出现的信息窗口标记。
for (var alphabet in window.towns) {
for (var town in window.towns[alphabet]) {
var info = window.towns[alphabet][town].town_info;
if (info !== undefined &&
typeof info !== undefined &&
info.google_maps !== undefined &&
typeof info.google_maps !== undefined) {
var lat = info.google_maps.lat,
lng = info.google_maps.lng;
info.marker =
new window.google.maps.Marker({
position: new window.google.maps.LatLng(lat,lng),
map: map,
title: window.towns[alphabet][town].post_title,
icon: icon_image
});
info.marker.iwindow =
new window.google.maps.InfoWindow({
content: '<strong><a href="#'+
window.towns[alphabet][town].post_title
.replace(' ','-','g').toLowerCase()+
'" class="town">'+
window.towns[alphabet][town].post_title+
'</a></strong>'
});
window.google.maps.event.addListener(info.marker, 'click', function() {
this.iwindow.open(map,this);
});
}
}
}
代码工作正常。但是,我得到一个JSLint错误,&#34;不要在循环中生成函数&#34;,这是有道理的。当匿名函数取决于this
的值等于当前info.marker
时,如何转换代码以避免在循环中创建函数?
答案 0 :(得分:2)
您可以在循环之前定义一个小函数,然后在循环中引用该局部函数:
循环之前:
function handleMarkerClick() {
this.iwindow.open(map,this);
}
然后,在循环中:
for (var alphabet in window.towns) {
for (var town in window.towns[alphabet]) {
// ....
window.google.maps.event.addListener(info.marker, 'click', handleMarkerClick);