Javascript 全局变量不变
我使用javascript获取我的当前位置Javascript 全局变量不变,javascript,Javascript,我使用javascript获取我的当前位置(LngLat)和Im使用全局变量保存Lng或Lang 它在函数show()中发生变化但在完成时返回到1,并且y没有改变 <!DOCTYPE html> <html> <body> <p>Click the button to get your coordinates.</p> <button onclick="getLocation()">Try It</button&g
(LngLat)代码>和Im使用全局变量保存Lng或Lang
它在函数show()中发生变化代码>但在完成时返回到1,并且y
没有改变
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
var y=1;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(show);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function show(p) {
y=p.coords.latitude;
//window.alert(y);
x.innerHTML = "Latitude: " + p.coords.latitude +
"<br>Longitude: " + p.coords.longitude;
}
window.alert(y);//<-- here is the problem , I don't want it to alert 1 !
单击按钮获取您的坐标
试试看
var x=document.getElementById(“演示”);
变量y=1;
函数getLocation(){
if(导航器.地理位置){
navigator.geolocation.getCurrentPosition(显示);
}否则{
x、 innerHTML=“此浏览器不支持地理位置。”;
}
}
功能表演(p){
y=p坐标纬度;
//窗口警报(y);
x、 innerHTML=“纬度:”+p.coords.Latitude+
“
经度:”+p.coords.Longitude;
}
窗口警报(y)// 请看这一点:
function show(p) {
y=p.coords.latitude;
//window.alert(y);
x.innerHTML = "Latitude: " + p.coords.latitude +
"<br>Longitude: " + p.coords.longitude;
startApp();
}
function startApp(){
window.alert(y);
// do whatever else you want
}
功能显示(p){
y=p坐标纬度;
//窗口警报(y);
x、 innerHTML=“纬度:”+p.coords.Latitude+
“
经度:”+p.coords.Longitude;
startApp();
}
函数startApp(){
窗口警报(y);
//你还想做什么就做什么
}
由于地理位置是异步的,因此将执行您的警报语句。地理位置尚未完成,因此未更新y
值……我如何解决此问题@Arunpjohny通过不向外部显示或其他功能发出警报来修复它。除非你点击按钮,否则你不会执行任何操作如果我错了,请纠正我,但是你调用函数show一次,并且你从未分配p,因此你不会给show一个参数。我想要一个纯金制的马桶座圈,但这不在计划之内。。。