我想访问变量 lat 和 var lng,如下面的代码所示,请建议我在 .load 中访问这些变量的正确方法
$(document).ready(function(){
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var lat= position.coords.latitude;
var lng= position.coords.longitude;
}
$(".content").load("page1.php?latitude="+lat+"&longitude="+lng);
});
我想调用 var lat 和 var lng,如下面的代码所示,请建议我在 .load 中调用此变量的正确方法
最佳答案
getCurrentPosition
函数是异步的 - 稍后调用回调并继续执行函数的其余部分。
因此,对 .load
的调用应该在 showPosition
函数本身内进行。
不要忘记您还必须调用 getLocation()
来启动整个过程。
为了方便起见,这里有一个未经测试的插件包装器,我刚刚将它转换为 Promise 接口(interface)的 getCurrentLocation
调用:
(function($) {
$.geolocate = function(options) {
var def = $.Deferred();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(def.resolve, def.reject, options);
} else {
def.reject("location not available");
}
return def.promise();
};
})(jQuery);
用法:
$.geolocate().done(function(pos) {
// use pos here
var lat = pos.coords.latitude;
var lng = pos.coords.longitude;
...
}).fail(function(err) {
// 'err' is a PositionError object (if supported but not permitted)
// or a string if geolocation isn't even supported.
});
关于javascript - 访问 jQuery document.ready() 中的 JavaScript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24416841/