[英]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.