gpt4 book ai didi

javascript - javascript中定义的全局变量再次变为未定义

转载 作者:行者123 更新时间:2023-11-30 08:07:54 25 4
gpt4 key购买 nike

<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&region=vi&language=vi">
</script>

<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
var map;
</script>
<style type="text/css">
html {
height: 100%;
}

body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>

<body onload="initialize()">
<div id="map_canvas" style="width: 100%; height: 100%"></div>

<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(10.79, 826.694),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
</script>

<script>
alert(map);
</script>

</body>
</html>

我的几个函数需要使用 map 变量,但是,我不断收到警告,提示 map 变量未被识别。我怎样才能让浏览器记住 map 是在 map = new google.maps.Map(document.getElementById("map_canvas"),
map 选项);
谢谢

最佳答案

那是因为你在 onLoad 上调用了函数 initialize(),这意味着映射变量在 onLoad 时被赋值。但是脚本

<script>            
alert(map);
</script>

onLoad 被触发之前被调用

尝试:

<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(10.79, 826.694),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);


alert(map);
}

</script>

关于javascript - javascript中定义的全局变量再次变为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14964611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com