简体   繁体   中英

How to store a variable value obtained in home page across all pages?

I am using jquery to fetch inner html value of a div in home page, and I want this value to be accessible in all pages. The problem i'm facing is that the div from which i'm getting the value is present only in home page, so when the script runs in other page, the value will be undefined as the div is not present.

The issue is, they are displaying a message in bottom of home page and we want it to be displayed in top part of all pages. so I used jquery to extract the text content and display it in top part, but when we go to other pages, the script fails as the bottom of that page wont have the message.

store it in a local storage:

localStorage.setItem('myItem', myValue);

and then you could Access this item on all pages

var item = localStorage.getItem('myItem');

https://developer.mozilla.org/de/docs/Web/API/Window/localStorage

You can use web storage objects like: sessionStorage or localStorage , but be careful with the data you store, which determines which method to use.

  • Data in sessionStorage is cleared when the page session ends.
  • Data stored in localStorage has no expiration time.

You can use Window localStorage Property as solution to your problem. Another option is sessionStorage . It depends what you trying to achieve. Look at the definition for both of them and use appropriate.

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