我有一个相当大的脚本,可以使用gmap3插件生成地图。在插件中,通常会应用多个地图标记,如下所示。我知道这适用于静态数据。
marker:{
values:[
{address:"555 Anywhere Rd Port Clinton, OH", data:'<h4>Some Data 1</h4>'},
{address:"556 Anywhere Rd Port Clinton, OH", data:'<h4>Some Data 2</h4>'},
{address:"557 Anywhere Rd Port Clinton, OH", data:'<h4>Some Data 3</h4>'}
]
}
当我尝试在每个循环外传递数组
markerValues
时,问题开始了,并且返回空值。这是我的完整代码:
/****************************************
*** DEALER LOCATOR MAP
****************************************/
(function($){
jQuery(document).ready(function(){
var tableRows = [];
var headersText = [];
var $headers = $("th");
var markerValues = {};
var $rows = $("#table tbody tr").each(function(index) {
$cells = $(this).find("td");
tableRows[index] = {};
$cells.each(function(cellIndex) {
if(headersText[cellIndex] === undefined) {
headersText[cellIndex] = $($headers[cellIndex]).text();
}
tableRows[index][headersText[cellIndex]] = $(this).text();
});
});
var tableData = {
"tableData": tableRows
};
$(function(){
$.each(tableData["tableData"], function(key, value){
markerValues = {
address: value.STREET+" "+value.CITY+","+value.STATE+" "+value.ZIP,
data: '<p>'+value.NAME+'<br />'+value.STREET+'<br />'+value.CITY+', '+value.STATE+'<br /> '+value.ZIP+'<br />'+value.TEL+'</p>'
};
});
});
console.log( markerValues );
$(function(){
$('#map_canvas').gmap3({
map:{
options:{
zoom: 3,
center: [41.374774, -83.651323],
streetViewControl: true,
mapTypeId: google.maps.MapTypeId.TERRAIN,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
}
},
marker:{
values:[markerValues],
options:{
draggable: false,
/*icon: "/static/images/mapmarker.png"*/
},
events:{
click: function(marker, event, context){
$(this).gmap3({
clear:"overlay"
});
$(this).gmap3({
overlay:{
latLng: marker.getPosition(),
options:{
content: '<div id="small_infowindow"><div class="row-fluid"><div class="span12">'+(context.data)+'</div></div></div>',
offset:{
y: -30,
x: 30
}
}
}
});
$(this).gmap3('get').panTo(marker.getPosition());
},
dblclick: function() {
$(this).gmap3({
clear:"overlay"
});
}
},
}
});
});
});
})(jQuery);
最佳答案
该变量在循环外不可访问
$.each(tableData["tableData"], function(key, value){
var markerValues = {
address: value.STREET+" "+value.CITY+","
+value.STATE+" "+value.ZIP,
data: '<p>'+value.NAME+'<br />'+value.STREET+'<br />'
+value.CITY+', '+value.STATE+'<br /> '+value.ZIP+'<br />'
+value.TEL+'</p>'
};
console.log( markerValues );
});
您应该在循环外部,第9行之前定义它(使用“ var”)
关于javascript - 每个循环外可用的var在控制台中返回空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23502705/