如何访问第二个脚本中的第一个脚本中的变量(在本例中为map )
我不能在一个脚本中做到这一点,因为:
module类型;没有它,import就不能工作。module类型,因为里面的函数必须在HTML中可见。(模块脚本中的函数不可见。)。
地图加载脚本:
<script type="module">
import { Map, NavigationControl, Marker, LngLatBounds } from 'https://cdn.skypack.dev/maplibre-gl';
var map = new Map({
container: 'map',
center: [ myLatLng.lng, myLatLng.lat ],
zoom: 13
});
</script>同一文件中的另一个脚本:
<script>
function setReaction(reactionNumber) {
// code
}
</script>发布于 2021-05-06 09:50:14
带有script的type=module是“封装”的,所有变量声明都不是自动分配给Window对象的。
你可以根据自己来分配,
<script type="module">
import { Map, NavigationControl, Marker, LngLatBounds } from 'https://cdn.skypack.dev/maplibre-gl';
window.map = new Map({
container: 'map',
center: [myLatLng.lng, myLatLng.lat],
zoom: 13
});
</script>但是,请注意,浏览器并没有保证使用import的脚本与其他脚本之间的任何事情,这意味着在您的情况下,您需要“等待”远程导入完成,然后运行依赖于导入结果的代码。
在下面的示例中,我使用了import()语法,它返回一个Promise,这是我在全局窗口对象上指定的承诺,您应该使用它。
<button onclick="checkMap()" type="button">Test</button>
<div id='map'></div>
<script type="module">
window.mapResolver = import('https://cdn.skypack.dev/maplibre-gl').then(
({ Map, NavigationControl, Marker, LngLatBounds }) => {
var map = new Map({ container: 'map', center: [0, 0], zoom: 13 });
return map;
}
);
</script>
<script>
function checkMap() {
window.mapResolver.then((map) => {
console.log(map)
})
}
</script>
https://stackoverflow.com/questions/67415361
复制相似问题