我正在尝试将 Geolocation API 与 Jquery Mobile 结合使用。如果我从浏览器直接浏览到我的页面,一切都会正常。
但是,如果我从另一个页面导航到它,它不会加载。
此外,如果我使用“pageinit”命令删除该代码行,我会遇到相同的问题/错误,但如果我刷新页面,它将加载。
我知道这与通过 AJAX 处理 DOM 的方式有关,但我似乎无法让它按照它应该/我想要的方式工作。
<!DOCTYPE html>
<html>
<head>
<title>My Location</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.js"></script>
</head>
<body>
<div data-role="page" id="geoPage">
<script type="text/javascript">
$("#geoPage").live("pageinit", function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
error('Geolocation not supported');
}
});
function success(position) {
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeControl: false,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mapcanvas = $('#mapcanvas');
var map = new google.maps.Map(mapcanvas[0], myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"I am here!"
});
//alert(latlng);
}
function error(msg) {
var errMsg = typeof msg == 'string' ? msg : "Geolocation failed";
$('#msg').html(errMsg);
}
$("#continue7").click(function(e){
$.mobile.changePage( "extension.htm", { transition: "slide"} );
});
</script>
<div data-role="header">
<h1>My Location</h1>
</div>
<div data-role="content">
<div id="msg"></div>
<div id="mapcanvas" style="height: 250px; width:250px;"></div>
<input id="continue7" type="button" value="Conintue" />
</div>
</div>
</body>
</html>
最佳答案
documentation如何处理 pageinit 事件与您的方法略有不同——至少是我正在查看的文档部分。他们的建议是您可以像这样编码:
$( document ).delegate("#geoPage", "pageinit", function() {
// Handle it
}
如果您想以这种方式绑定(bind),文档听起来像是您已将函数放置在最佳位置。
编辑:
值得注意的是,this particular page完全按照您所显示的方式描述绑定(bind)(但将 event
添加到匿名函数中,我认为这不会影响您的情况)。这让我相信,当您从另一个页面导航并且该页面显示“不工作”时,您的开发人员工具控制台中可能会出现 javascript 错误。请务必在您选择的开发者工具中检查这一点。
编辑:
您的解决方案是您需要将您的谷歌地图javascript“include”包含在 data-role='page'
中的某个位置元素。每次加载 AJAX 页面时,Jquerymobile 都会忽略除此之外的所有内容。或者,您可以将进入此页面的所有链接变成 data-ajax="false"
.
在 data-role="page"中包含以下行内部或将其包含在 html <head>
中每个页面。
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
一定要真正阅读并理解原始链接。最佳做法是您有相同的 <head>
每个页面的元素并包含它而不是复制粘贴它。
关于html - Jquery Mobile "pageinit"未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10281442/