Home > Web Front-end > JS Tutorial > JS method to implement local storage of information (based on localStorage and userData)

JS method to implement local storage of information (based on localStorage and userData)

高洛峰
Release: 2017-02-20 16:34:05
Original
1448 people have browsed it

This article mainly introduces the method of JS to implement local storage of information. It implements the local storage function based on localStorage and userData. Friends in need can refer to it.

The example of this article describes the method of JS to implement local storage of information. . Share it with everyone for your reference. The details are as follows:

With the rapid development of WEB applications, local storage of some data has become an important requirement. There are many implementation solutions. The most common one is cookie. Everyone It is often used, but the shortcomings of cookies are obvious. Other solutions include: userData in IE6 and above, globalStorage in Firefox, and local storage in Flash. Except for Flash, the others have some compatibility issues. .

sessionStorage and localStorage

Web Storage actually consists of two parts: sessionStorage and localStorage.

sessionStorage is used to locally store data in a session. These data can only be accessed by pages in the same session and the data will be destroyed when the session ends. Therefore sessionStorage is not a persistent local storage, only session-level storage.

localStorage is used for persistent local storage. Unless the data is actively deleted, the data will never expire.

userData

Syntax:

XML <br>HTML <ELEMENT STYLE="behavior:url('#default#userData')" ID=sID><br>Scripting object .style. behavior = "url('#default#userData')"<br>object .addBehavior ("#default#userData")</p> <p><span style="color: #0000ff"><strong>Attribute:</strong></span></p> <p>expires Sets or gets the expiration date of userData behavior saved data. <br>XMLDocument Gets a reference to XML. </p> <p><span style="color: #0000ff"><strong>Method:</strong></span></p> <p><code>getAttribute()</code> Get the specified attribute value. <br><code>load(object) </code>Load the stored object data from the userData storage area. <br><code>removeAttribute() </code>Remove the specified attribute of the object. <br><code>save(object) </code>Store object data to a userData storage area. <br><code>setAttribute() </code>Set the specified attribute value. <br></p> <p><strong>localStorage</strong></p> <p><span style="color: #0000ff"><strong>Method: </strong></span></p> <p><code>localStorage.getItem(key ):</code>Get the value of the local storage of the specified key<br><code>localStorage.setItem(key, value):</code>Store the value into the key field<br><code>localStorage.removeItem(key):</code>Delete the value stored locally for the specified key</p> <p>Encapsulation</p> <p class="jb51code"><br></p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;">localData = { hname:location.hostname?location.hostname:&#39;localStatus&#39;, isLocalStorage:window.localStorage?true:false, dataDom:null, initDom:function(){ //初始化userData if(!this.dataDom){ try{ this.dataDom = document.createElement(&#39;input&#39;);//这里使用hidden的input元素 this.dataDom.type = &#39;hidden&#39;; this.dataDom.style.display = "none"; this.dataDom.addBehavior(&#39;#default#userData&#39;);//这是userData的语法 document.body.appendChild(this.dataDom); var exDate = new Date(); exDate = exDate.getDate()+30; this.dataDom.expires = exDate.toUTCString();//设定过期时间 }catch(ex){ return false; } } return true; }, set:function(key,value){ if(this.isLocalStorage){ window.localStorage.setItem(key,value); }else{ if(this.initDom()){ this.dataDom.load(this.hname); this.dataDom.setAttribute(key,value); this.dataDom.save(this.hname) } } }, get:function(key){ if(this.isLocalStorage){ return window.localStorage.getItem(key); }else{ if(this.initDom()){ this.dataDom.load(this.hname); return this.dataDom.getAttribute(key); } } }, remove:function(key){ if(this.isLocalStorage){ localStorage.removeItem(key); }else{ if(this.initDom()){ this.dataDom.load(this.hname); this.dataDom.removeAttribute(key); this.dataDom.save(this.hname) } } } }

Copy after login


The method of use is very simple, this section Just set, get, remove.

The demo code involved is as follows:


<script type="text/javascript">
(function() {
  window.localData = {
    hname : location.hostname ? location.hostname : &#39;localStatus&#39;,
    isLocalStorage : window.localStorage ? true : false,
    dataDom : null,
    initDom : function() {
      if (!this.dataDom) {
        try {
          this.dataDom = document.createElement(&#39;input&#39;);
          this.dataDom.type = &#39;hidden&#39;;
          this.dataDom.style.display = "none";
          this.dataDom.addBehavior(&#39;#default#userData&#39;);
          document.body.appendChild(this.dataDom);
          var exDate = new Date();
          exDate = exDate.getDate() + 30;
          this.dataDom.expires = exDate.toUTCString();
        } catch (ex) {
          return false;
        }
      }
      return true;
    },
    set : function(key, value) {
      if (this.isLocalStorage) {
        window.localStorage.setItem(key, value);
      } else {
        if (this.initDom()) {
          this.dataDom.load(this.hname);
          this.dataDom.setAttribute(key, value);
          this.dataDom.save(this.hname)
        }
      }
    },
    get : function(key) {
      if (this.isLocalStorage) {
        return window.localStorage.getItem(key);
      } else {
        if (this.initDom()) {
          this.dataDom.load(this.hname);
          return this.dataDom.getAttribute(key);
        }
      }
    },
    remove : function(key) {
      if (this.isLocalStorage) {
        localStorage.removeItem(key);
      } else {
        if (this.initDom()) {
          this.dataDom.load(this.hname);
          this.dataDom.removeAttribute(key);
          this.dataDom.save(this.hname)
        }
      }
    }
  };
  var text = document.getElementById(&#39;localDataHook&#39;);
  var btn = document.getElementById(&#39;clearBtnHook&#39;);
  window.onbeforeunload = function() {
    localData.set(&#39;beiyuuData&#39;, text.value);
  };
  btn.onclick = function() {
    localData.remove(&#39;beiyuuData&#39;);
    text.value = &#39;&#39;
  };
  if (localData.get(&#39;beiyuuData&#39;)) {
    text.value = localData.get(&#39;beiyuuData&#39;);
  }
})();
</script>
Copy after login


There is also a more practical technology to prevent the page from closing. , display the page closing confirmation pop-up box, the reference code is as follows:


window.onbeforeunload = function() {
  if (!canLeavePage()) {
    return (&#39;确认离开当前页面吗?未保存的数据将会丢失!&#39;);
  }
Copy after login

I hope this article will be helpful to everyone in JavaScript programming.

For more JS methods to implement local storage of information (based on localStorage and userData), please pay attention to the PHP Chinese website!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template