How to save the state of a javascript variable that is used in multiple html pages

前端 未结 3 2027
执笔经年
执笔经年 2021-01-13 10:17

I am trying to make an application in phonegap. I have made a custom.js javascript file which have some functions as

function func1(){....}
function func2(){         


        
相关标签:
3条回答
  • 2021-01-13 10:33

    in modern browsers you can use localStorage for that

    var get = function (key) {
      return window.localStorage ? window.localStorage[key] : null;
    }
    
    var put = function (key, value) {
      if (window.localStorage) {
        window.localStorage[key] = value;
      }
    }
    

    use get and put to store value to the local storage of most modern browsers..

    0 讨论(0)
  • 2021-01-13 10:37

    Store the values in localstorage and reference it from there.

    function first() {
        localStorage.setItem('myItem', "something you want to store");
    }
    
    function second() {
        myValue = null;
        if (localStorage.getItem('myItem')) {
            myValue = localStorage.getItem('myItem');
        }
    }
    
    0 讨论(0)
  • 2021-01-13 10:52

    The easier and preferred method would be to use window.localStorage for storing site wide variables. To accommodate older browsers as well, you can maybe consider having cookies as a secondary storage location.

    // 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];
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题