是否可以从另一个 HTML 文件中的 JS 脚本加载变量? [英] Is it possible to load a variable from a JS script in another HTML file?

查看:25
本文介绍了是否可以从另一个 HTML 文件中的 JS 脚本加载变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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");

参见:如何从 GET 参数中获取值?

这篇关于是否可以从另一个 HTML 文件中的 JS 脚本加载变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆