[英]How to save the state of a javascript variable that is used in multiple html pages
我正在嘗試在phonegap中創建一個應用程序。 我已經制作了一個custom.js javascript文件,其中包含一些函數
function func1(){....}
function func2(){....}
所有這些功能都將用於兩個不同的html頁面。 在第一個HTML頁面中,我在func1中使用了一個變量,它正在進行一些操作。 在第二頁中,我想在func2中以func1的狀態訪問它。 但我無法做到。 我在兩個html頁面中都包含custom.js. 我已經讀過,當在多個頁面中使用時,javascript文件會被重置/刷新。 任何人都可以給我一個例子,說明如何在func1中保存變量的狀態,然后在func1中的func2(在不同的HTML頁面中)訪問該變量。 我也讀過有關視圖狀態的內容。 但它對我來說都不起作用。 請幫忙...
將值存儲在localstorage中並從那里引用它。
function first() {
localStorage.setItem('myItem', "something you want to store");
}
function second() {
myValue = null;
if (localStorage.getItem('myItem')) {
myValue = localStorage.getItem('myItem');
}
}
在現代瀏覽器中,您可以使用localStorage
var get = function (key) {
return window.localStorage ? window.localStorage[key] : null;
}
var put = function (key, value) {
if (window.localStorage) {
window.localStorage[key] = value;
}
}
使用get和put將值存儲到大多數現代瀏覽器的本地存儲中。
更簡單和首選的方法是使用window.localStorage
存儲站點范圍的變量。 為了適應舊版瀏覽器,您可以考慮將cookie作為輔助存儲位置。
// credits to http://mathiasbynens.be/notes/localstorage-pattern
var hasStorage = (function() {
try {
localStorage.setItem(mod, mod);
localStorage.removeItem(mod);
return true;
} catch(e) {
return false;
}
}());
function setSiteWideValue(_key, _value) {
if(hasStorage) {
localStorage[_key] = _value;
}
else {
document.cookie = _key+'='+_value+'; expires=<date-here>; path=/; ;domain=<.yourdomain>';
}
}
function getSiteWideValue(_key) {
if(hasStorage) {
return localStorage[_key];
}
else {
if(document.cookie.indexOf(_key+'=') != -1) {
return document.cookie.split(_key+'=')[1].split(';')[0];
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.