是否可以从另一个 HTML 文件中的 JS 脚本加载变量? [英] Is it possible to load a variable from a JS script in another HTML file?
问题描述
我在 HTML 文件中有一个 JS 脚本,它从 API 获取某个值并放入一个变量.我想将具有相同值的变量放在另一个 HTML 文件上(新的 HTML 文件是从上一页的按钮加载的).有什么办法吗?
I have a JS script inside a HTML file that get a certain value from API and put on a variable. I want to put that same variable with the value on another HTML file (The new HTML file is loaded from a button in the previous page). Is there any way to to that?
推荐答案
我能想到两个简单的方法.
I can think of two easy ways.
1.) 尝试 sessionStorage:sessionStorage.setItem('key', variable);
将变量值存储在浏览器会话存储中.sessionStorage.getItem('key');
将返回该变量的设置值.
1.) Try out sessionStorage: sessionStorage.setItem('key', variable);
will store the variable value in the browser session storage. sessionStorage.getItem('key');
will return the set value of said variable.
参见:https://developer.mozilla.org/de/docs/Web/API/Window/sessionStorage
2.) 将变量值添加到您的 url www.yourdomain.com?key=value
并从您的第二个脚本中检索它.
2.) Add the variable value to your url www.yourdomain.com?key=value
and retrieve it from your second script.
const urlString = window.location.href;
const url = new URL(urlString);
const value = url.searchParams.get("key");
这篇关于是否可以从另一个 HTML 文件中的 JS 脚本加载变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!