如何从另一个 javascript 文件的函数内部访问 var?



我在堆栈上看到过类似的问题,但我无法为我的用例实现解决方案。

对于某些上下文,我试图将纬度/经度变量存储在一个名为cords(Script.js(的数组中:

function geoFindMe() {
const status = document.querySelector('#status');
const mapLink = document.querySelector('#map-link');
mapLink.href = '';
mapLink.textContent = '';
function success(position) {
var latitude  = position.coords.latitude;
var longitude = position.coords.longitude;
var cords = [{lat : latitude, long : longitude}];

console.log(cords);
status.textContent = '';
mapLink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`;
mapLink.textContent = `Latitude: ${latitude} °, Longitude: ${longitude} °`;
}
function error() {
status.textContent = 'Unable to retrieve your location';
}
if(!navigator.geolocation) {
status.textContent = 'Geolocation is not supported by your browser';
} else {
status.textContent = 'Locating…';
navigator.geolocation.getCurrentPosition(success, error);
//navigator.geolocation.watchPosition(success, error);
}
}
document.querySelector('#find-me').addEventListener('click', geoFindMe);

我正在尝试访问这个变量并将其保存到本地文本文件(Script2.js(:

function saveStaticDataToFile() {
console.log("Clicked")

var a = document.body.appendChild(document.createElement("a"));
a.download = "cords.txt";
a.href = "data:text/plain;base64," + btoa(JSON.stringify(cords));
a.innerHTML = "Save Cords";

}

document.querySelector('#filesaver').addEventListener('click', saveStaticDataToFile);

这是我在本地保存文件的方法,但我希望有人能帮助我如何做到这一点/最佳实践?

我尝试过一些事情,比如在函数外初始化跳线,以及在aysnc等待中的一些糟糕尝试。

如果你想尝试运行它:

<head></head>
<body>
<button id = "find-me">Show my location</button><br/>
<p id = "status"></p>
<a id = "map-link" target="_blank"></a>

<button id="filesaver">Click to Save</button>
<script src="script.js"></script>
<script src="script2.js"></script>
</body>

您可以在函数范围之外定义cords,使其可用于两个函数。解决方案是,在设计应用程序时,甚至在从浏览器获取cords之前,都不会尝试保存它。在用户从浏览器获取位置之前添加一些错误/信息。

var cords = null;
function geoFindMe() {
const status = document.querySelector('#status');
const mapLink = document.querySelector('#map-link');
mapLink.href = '';
mapLink.textContent = '';
function success(position) {
var latitude  = position.coords.latitude;
var longitude = position.coords.longitude;
cords = [{lat : latitude, long : longitude}];

console.log(cords);
status.textContent = '';
mapLink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`;
mapLink.textContent = `Latitude: ${latitude} °, Longitude: ${longitude} °`;
}
function error() {
status.textContent = 'Unable to retrieve your location';
}
if(!navigator.geolocation) {
status.textContent = 'Geolocation is not supported by your browser';
} else {
status.textContent = 'Locating…';
navigator.geolocation.getCurrentPosition(success, error);
//navigator.geolocation.watchPosition(success, error);
}
}
document.querySelector('#find-me').addEventListener('click', geoFindMe);
function saveStaticDataToFile() {
console.log("Clicked")

// Show an error/info here to the user
if (!cords) console.log('Please get the location first');

var a = document.body.appendChild(document.createElement("a"));
a.download = "cords.txt";
a.href = "data:text/plain;base64," + btoa(JSON.stringify(cords));
a.innerHTML = "Save Cords";

}

document.querySelector('#filesaver').addEventListener('click', saveStaticDataToFile);
<head></head>
<body>
<button id = "find-me">Show my location</button><br/>
<p id = "status"></p>
<a id = "map-link" target="_blank"></a>

<button id="filesaver">Click to Save</button>
</body>

html文件中的脚本作为一个脚本工作-您可以在全局范围内声明变量,并在html 上的不同脚本中从任何位置访问它

index.html:

<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Location</title>
</head>
<body>
<button id="find-me">Show my location</button><br />
<p id="status"></p>
<a id="map-link" target="_blank"></a>
<br>
<!-- i used a link directly here so you dont have to click twice to download the file -->
<a id="filesaver" href="">Click to Save</a>
<!-- this script works like the same script even they are from different files/scripts -->
<script src="script.js"></script>
<script src="script2.js"></script>
</body>
</html>

script.js:

// getting element from dom
// global scope constants
const FILE_SAVER = document.querySelector('#filesaver');
const STATUS = document.querySelector('#status');
const MAP_LINK = document.querySelector('#map-link');
let cords = []; // global scope variable so you can access it from the scripts below this one
FILE_SAVER.style.display = 'none'; // hiding the 'save file button' until we get the coords
const success = (position) => {
const { coords: { latitude, longitude } } = position; // using ES6 syntax to make the code easy to read
STATUS.textContent = '';
MAP_LINK.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`;
MAP_LINK.textContent = `Latitude: ${latitude}°, Longitude: ${longitude}°`;
cords = [{ lat: latitude, long: longitude }]; // setting the cords in the global cords variable
FILE_SAVER.style.display = 'block'  // displaying the 'save file button'
}
const error = () => {
STATUS.textContent = 'Unable to retrieve your location';
}
const geoFindMe = () => {
if (!navigator.geolocation) {
STATUS.textContent = 'Geolocation is not supported by your browser';
} else {
STATUS.textContent = 'Locating...';
navigator.geolocation.getCurrentPosition(success, error);
}
}
document.querySelector('#find-me').addEventListener('click', geoFindMe);

script2.js:

const saveStaticDataToFile = () => {
// using FILE_SAVER constant from the first script `we can access it from here bc we declare in global scope`
FILE_SAVER.download = "cords.txt";
FILE_SAVER.href = "data:text/plain;base64," + btoa(JSON.stringify(cords));
}
document.querySelector('#filesaver').addEventListener('click', saveStaticDataToFile);

相关内容

  • 没有找到相关文章

最新更新