简体   繁体   中英

Use variable from another js file

How can I use a variable that is creats in first.js in two.js? Notice: the two files are linked to two different html pages.

I didn't try anything cause I don't have any idea Notice: I can't use the same js file because there's function that work for the first htmls file but I don't want them to work for the second one,that's why I'm using two js files

You can do it by exporting that variable and import it into another file

for exa- first.js

export const message = "Hello"; 

two.js

import { message } from "./utils.js";

You can use SessionStorage for persist value acros multiple pages.

You can save value using:

sessionStorage.setItem("Name", "Hiren");

You can get value using:

sessionStorage.getItem("Name");

You can't as soon as you leave first html page script reload and everything is set back to initial value.

Some workarounds are using localStorage/sessionStorage

Or you can create SPA(single page application) using react or vanilla js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM