且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以从另一个HTML文件中的JS脚本加载变量?

更新时间:2023-12-05 15:58:34

我可以想到两种简单的方法.

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参数中获取值?