是否可以从另一个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.)将变量值添加到您的网址 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");
请参阅:如何从GET参数中获取值?
这篇关于是否可以从另一个HTML文件中的JS脚本加载变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!