在 JqueryMobile 页面中,我将全局变量声明为 HTML 页面脚本中的数组
<script src="map.js"></script>
<script>
var longitude= new Array();
var latitude= new Array();
var time=new Array();
var date=new Array();
</script>
</head>
<body>
<div data-role="page" id="home">
<div data-theme="a" data-role="header" id="page-map">
<h3>
Route Map
</h3>
</div>
<div data-role="content" id="map-content">
<div id="map_canvas"></div>
</div><!-- /content -->
</div>
</body>
和外部 map.js 文件包含
$(document).delegate("#home", "pagebeforecreate", function(){
console.log("pagebeforecreate :");
var jqxhr = $.getJSON("file:///android_asset/www/da.json", function(data) {
$.each(data, function(i,ele)
{
longitude.push(ele.longitude);
latitude.push(ele.latitude);
time.push(ele.time);
date.push(ele.date);
});
}).done(function() { console.log( "second success" ); })
.fail(function() { console.log( "error" ); alert("parsing error");})
.always(function() { console.log( "complete" ); });
jqxhr.complete(function(){ console.log("second complete");
console.log("longitude"+longitude);
});
});
$(document).delegate("#home", "pageinit", function(){
console.log("pageinit :"+longitude.length+" and "+latitude.length);
var center= new google.maps.LatLng(latitude[0],longitude[0]);
var myOptions = {
zoom: 15,
center: center,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var polylineCoordinates=new Aaary();
for(var i=0;i<longitude.length;i++)
{
polylineCoordinates.push(new google.maps.LatLng(latitude[i],longitude[i]));
}
var polyline = new google.maps.Polyline({
path: polylineCoordinates,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
editable: true
});
polyline.setMap(map);
});
$(document).delegate("#home", "pagebeforeshow", function(){
//longitude
console.log("pagebeforeshow :"+lon.length+" and "+lat.length);
});
当我运行此代码时,必须执行生命周期模式 pagebeforecreate -> pageinit -> pagebeforeshow ->pageshow。对我来说一样,但发生的事情是,Pagebeforecreate 中的任何代码(ajax)都没有完成它的执行到下一个并访问 pageinit 块,因此我从 json 文件解析的数据被推送到全局变量纬度和经度是在 pageinit 中被视为 null。那么,正确的方法是什么?
see my logcat file
I/Web Console(4201): pagebeforecreate : at file:///android_asset/www/parse.js:2
I/Web Console(4201): pageinit :0 and 0 at file:///android_asset/www/parse.js:23
I/Web Console(4201): pagebeforeshow :0 and 0 at file:///android_asset/www/parse.js:27
I/Web Console(4201): pageshow: 0 and 0 at file:///android_asset/www/parse.js:73
I/Web Console(4201): second success at file:///android_asset/www/parse.js:13
I/Web Console(4201): complete at file:///android_asset/www/parse.js:15
I/Web Console(4201): second complete at file:///android_asset/www/parse.js:17
I/Web Console(4201): longitude77.652633,77.651281,77.6492,77.647741,77.647312,77.647011,77.646861,77.646689,77.645016,77.643578,77.642097,77.640831,77.640917 at file:///android_asset/www/parse.js:18