为什么我的变量不取函数中的值
Why does my variables dont take the value in the function?
我想在屏幕上显示var经度和纬度,但我认为函数是最后执行的,我被初始值卡住了。目标是在屏幕上打印浏览器返回的地理位置的精确值。谢谢
<!DOCTYPE html>
<head>
<script>
var longitude = "10";
var latitude = "20";
</script>
</head>
<html>
<body onload="getLocation()">
<script>
var longitude = "30";
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
alert('aaab:' +longitude);
});
}else {
alert("Geolocation API is not supported in your browser.");
}
}
</script>
<script>
alert("ccc");
document.write (longitude);
document.write (latitude);
</script>
</body>
</html>
我知道它在函数内工作,但有什么方法可以在函数外使用这些变量吗?我只想把它们存储在一个全局变量中,可以在任何地方调用。感谢
document.write在更新它的代码运行之前执行。您需要在回调中执行document.write,如下所示:
<!DOCTYPE html>
<head>
<script type='text/javascript'>
var longitude = "10";
var latitude = "20";
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
document.write(latitude+" / "+longitude);
});
}else{
alert("Geolocation API is not supported in your browser.");
}
}
</script>
</head>
<body onload="getLocation()">
</body>
</html>
试试这个:
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocation);
}else {
alert("Geolocation API is not supported in your browser.");
}
}
function displayLocation(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
alert('aaab:' +longitude);
}
在编写经度和纬度时,地理位置回调可能尚未调用。也许您可以使用jQuery将正确的值写入屏幕。。。
<script>
var longitude = "30";
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
//alert('aaab:' +longitude);
// Use jQuery to write your values to the html
$("#longitude").html(longitude);
$("#latitude").html(latitude);
});
}else {
alert("Geolocation API is not supported in your browser.");
}
}
</script>
<html>
...
<body onload="getLocation()">
<div id="longitude"></div>
<div id="latitude"></div>
</body>
</html>
相关文章:
- 可以Resharper在我的javascript函数声明中添加分号
- 为什么我的JavaScript堆栈排序函数不起作用
- 加速我的复杂函数绘图仪(canvas+javascript)
- 为什么不是'我的函数在解析云代码中工作吗?当我在Angular和Express中测试时,它是有效的
- 使用JAVASCRIPT转换货币.可以't通过我的函数设置转换后的输入文本字段的值
- 为什么我的控制器没有启动函数.js脚本
- 为什么我的函数没有被调用呢
- 由于某种原因,我的JavaScript函数无法工作
- 我需要一个jQuery函数来只工作在700px以上的屏幕大小,无法在我的代码中发现错误
- 我应该如何声明我的自调用函数
- 为什么我的函数没有返回准确的计数
- 为什么我的回调函数没有运行
- 为什么我的jQuery点击函数没有触发
- 我的函数返回“未定义”
- 为什么我的JavaScript函数没有返回选中的数组值
- 用我的函数jquery给出数据/参数
- 为什么我的javascript地理编码函数返回空白结果
- 从未达到我的函数调用-ReactJs 0.12.0
- 我的函数不会返回要保存在数组中的对象
- 我的徽章;如果“;为什么没有调用关联的函数