[英]Change Javascript variable value from another file
嘿伙计们,我有一个名为 map.php 的文件,我想将代码中显示的中心值更改为从另一个名为 template.js 的 JS 文件传递的不同值。 以前,我使用设置属性和查询选择器 function 更改了其他 HTML 值的值,但我不知道如何访问 JavaScript 变量并更改值。 我不知道查询选择器 function 是否适用于选择 JavaScript 变量。 任何帮助表示赞赏。 非常感谢。
Javascript (map.php)
<script>
var map = new mapboxgl.Map({
container: 'map',
style:'mapbox://styles/joelcherian/ckkg9x7f2063917o1kexgn9ho',
center: [115.83333, -32.01667], // accept change from template.js
zoom: 12
});
</script>
You can access the variable from the other file if they share the same scope: your declaration of map is global (the scope is window) so you can access it just by using it: map.flyTo({ center: yourCenterHere });
.
唯一需要注意的是调用变量的脚本在创建后运行。
现在你有两种方法:
map.php
中使用它,但在需要它的之前包括您的脚本( window
字是可选的,因为它是默认的全局范围)。// template.js
window.myCenterVariable = yourCenterHere;
<script src="template.js"></script>
<script>
var map = new mapboxgl.Map({
container: 'map',
style:'mapbox://styles/joelcherian/ckkg9x7f2063917o1kexgn9ho',
center: window.myCenterVariable,
zoom: 12
});
</script>
template.js
文件中:<script>
window.map = new mapboxgl.Map({
container: 'map',
style:'mapbox://styles/joelcherian/ckkg9x7f2063917o1kexgn9ho',
center: [115.83333, -32.01667],
zoom: 12
});
</script>
<!-- NOTE: I include template AFTER the above script has been executed -->
<script src="template.js"></script>
// template.js
window.map.flyTo({ center: yourCenterHere });
首先,您可以将代码写入template.js
文件。
const newValue = [0, 0];
module.exports.update = function(mapObj){
mapObj.center = newValue;
}
您可以在map.js
文件中编辑您的代码。
var r=require("./template.js");
var mapObj = {
container: 'map',
style:'mapbox://styles/joelcherian/ckkg9x7f2063917o1kexgn9ho',
center: [115.83333, -32.01667], // accept change from template.js
zoom: 12
};
r.update(mapObj);
var map = new mapboxgl.Map(mapObj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.