[英]Access JavaScript variables inside the jQuery document.ready()
我想訪問變量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()
來開始整個過程。
為方便起見,這是一個我未經測試的插件包裝程序,將getCurrentLocation
調用轉換為Promise接口:
(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.
});
您可以將它們移到.ready()
的范圍內:
$(document).ready(function(){
var lat;
var lng;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
lat= position.coords.latitude;
lng= position.coords.longitude;
}
$(".content").load("page1.php?latitude="+lat+"&longitude="+lng);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.