这真的让我发疯。为什么我的数组会失去作用域,将其移动到 for 循环中?请看一下这段代码,var 'marker' 在这个脚本的开头附近失去了作用域。欢迎任何想法。
<!DOCTYPE html>
<html>
<head>
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
//var cell={};
var cellcenter = new Array();
var lat = ''; var lng='';
$(document).ready(function(){
i=0;
$.getJSON('http://www.perivision.net/testing/containment/containment.php', function(data) {
var marker = new Array();
marker[0]=9;
$('#output').html('this works '+marker[0]);
for (index in data) {
i++;
$('#output').html(' this does not '+marker[0]);
for (element in data[index]) {
//console.log(element);
//console.log(data[index][element]);
if (element=="attribute8"){
lat=data[index][element];
}
if (element=="attribute9"){
//cell[i]=data[index][element];
lng=data[index][element];
cellcenter[i]=new google.maps.LatLng(lat,lng);
var myLatlng = new google.maps.LatLng(51.508742,-0.120850);
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map= new google.maps.Map(document.getElementById("googleMap"),mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:"Hello World!"
});
marker[i] = new google.maps.Marker({
position: cellcenter[i],
title:"Hello World!"+i
});
// To add the marker to the map, call setMap();
marker.setMap(map);
//marker[0].setMap(map);
marker[i].setMap(map);
//$('#output').html('re '+marker[0]);
//console.log('ping '+i+' '+cellcenter[i]);
}
}
}
});
});
function donothing(){
}
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
<button id="requestDataBtn">Get Data</button><br />
<div id='output'></div>
</body>
</html>