问题
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?
回答1:
I can think of two easy ways.
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.
See: https://developer.mozilla.org/de/docs/Web/API/Window/sessionStorage
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");
See: How to get the value from the GET parameters?
来源:https://stackoverflow.com/questions/62314910/is-it-possible-to-load-a-variable-from-a-js-script-in-another-html-file