当前位置:网站首页>JS local storage

JS local storage

2022-06-13 09:41:00 A-L-Kun

The local store

One 、 An introduction to

With the rapid development of Internet , Web based applications are becoming more and more popular , It's also becoming more and more complex , In order to meet all kinds of needs , Will often store a large amount of data locally ,HTML5 The specification puts forward relevant solutions

Local storage features

  1. The data is stored in the user's browser
  2. Set up 、 Easy to read 、 Set page refresh without losing data
  3. Relatively large capacity ,window.sessionStorage、window.localStorage about 20M
  4. Only strings can be stored , You can put objects JSON.stringify() Store after encoding

Two 、 sessionStorage

  1. The lifecycle is to close the browser window
  2. In the same window ( page ) Next, data can be shared
  3. Store and use in the form of key value pairs

1、 grammar

Store the data

sessionStorage.setItem(key, value);

get data

sessionStorage.getItem(key);

Delete data

sessionStorage.removeItem(key);

Empty data

sessionStorage.clear();

2、 Case study

<input type="text" name="name" id="" placeholder=" Please enter your name ">
    <button class="set"> Store the data </button>
<button class="get"> get data </button>
<button class="remove"> Delete data </button>
<button class="del"> Clear all data </button>
<script>
    var ipt = document.querySelector("input");
var set = document.querySelector(".set");
set.addEventListener("click", function() {
    
    //  When we click , You can store the data in the form 
    sessionStorage.setItem(String(Date.now()), ipt.value);
    ipt.value = "";
})
var get = document.querySelector(".get");
get.addEventListener("click", function() {
    
    //  When we click , You can get the values in the form 
    alert(sessionStorage.getItem("uName"));
})
var remove = document.querySelector(".remove");
remove.addEventListener("click", function() {
    
    //  When we click , You can remove specific values from the form 
    sessionStorage.removeItem("uName");
})
var del = document.querySelector(".del");
del.addEventListener("click", function() {
    
    //  When we click , You can clear all the data in the form 
    sessionStorage.clear();
})
</script>

3、 ... and 、 localStorage

  1. The life cycle takes effect permanently , Unless you delete , Otherwise, the closed page will always exist
  2. You can have multiple windows ( page ) share ( The same browser can share )
  3. Store in the form of key value pairs

1、 grammar

Store the data

localStorage.setItem(key, value);

get data

localStorage.getItem(key);

Delete data

localStorage.removeItem(key);

Empty data

localStorage.clear();
原网站

版权声明
本文为[A-L-Kun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202270525119975.html