Home Web Front-end JS Tutorial Five step-by-step ways to use localStorage and sessionStorage

Five step-by-step ways to use localStorage and sessionStorage

Jul 22, 2017 pm 04:57 PM
localstorage sessionstorage

Requirements: Locally record the last content entered by the user

Use key technology: localStorage

Step 1: Use jQuery’s ordinary writing method

1. JS code

// 获取window的localStorage对象var localS = window.localStorage;// 获取localStorage的值var getV = localS.getItem("value0"),
    getV2 = localS.getItem("value1");// 把获取到的值赋给对应的input$(".value0").val(getV);
$(".value1").val(getV2);// 键盘按键弹起就设置localStorage的值$(document).on("keyup",function(){// 一个输入框对应一个value值var va = $(".value0").val(),
        va2 = $(".value1").val();// 有多少个就设置setItem多少个localS.setItem("value0",va);
    localS.setItem("value1",va2);
});
Copy after login

2. Rendering

3. Well... it can be used, but here comes the problem. This JS code is written... it's a bit messy, and it won't be easy to maintain later! what to do? ? Is there any way to fix it? ?

Step 2: Use JS function method to write

1, JS code

 1 // 所用到的变量统一写在一起 2 var va,va2,getV,getV2; 3 // 设置localStorage方法 4 function localSet(){ 5     va = $(".value0").val(), 6     va2 = $(".value1").val(); 7     localStorage.setItem("value0",va); 8     localStorage.setItem("value1",va2); 9 };10 // 获取localStorage方法11 function localGet(){12     getV = localStorage.getItem("value0"),13     getV2 = localStorage.getItem("value1");14     $(".value0").val(getV);15     $(".value1").val(getV2);16 }17 // 键盘按键弹起就设置localStorage的值18 $(document).on('keyup',function(){19     localSet();20 });21 // 页面一加载就调用设置localStorage的方法22 localGet();
Copy after login

2. Rendering

3. Hmm... It’s easy to change it to a function It's easy to know which one is setting and which one is getting localStorage, which is okay. However, here comes the problem, I don’t want to use functions, I want to use object-oriented writing, what should I do? ?

The third step: JS object-oriented writing method

1. JS code

 1 // 所用到的变量统一写在一起 2 var va,va2,getV,getV2; 3 var localObj = { 4     // 设置localStorage方法 5     localSet : function(){ 6         va = $(".value0").val(), 7         va2 = $(".value1").val(); 8         localStorage.setItem("value0",va); 9         localStorage.setItem("value1",va2);10     },11     // 获取localStorage方法12     localGet : function(){13         getV = localStorage.getItem("value0"),14         getV2 = localStorage.getItem("value1");15         $(".value0").val(getV);16         $(".value1").val(getV2);17     }18 }19 $(document).on('keyup',function(){20     localObj.localSet();21 });22 // 页面一加载就调用设置localStorage的方法23 localObj.localGet();
Copy after login

2. Rendering

##3. Haha... Just change it and it will be fine. It’s quite simple! However, here comes the problem. If there are many input boxes that need to be recorded, wouldn't it mean that we have to write a lot of code? Can it be processed in a loop? ?

Step 4: Use for loop writing method

1. JS code

 1 var localObj = { 2     // 设置localStorage方法 3     localSet : function(){ 4         // 我这里测试用的,所以直接选中所有的input长度,实际使用换成相同类名即可 5         for (var i = 0; i < $("input").length; i++) { 6             // 这里要注意,所有的localStorage的key都要相同,只是数字不同而已 7             localStorage.setItem("value"+i,$(".value"+i).val()); 8         } 9     },10     // 获取localStorage方法11     localGet : function(){12         for (var i = 0; i < $("input").length; i++) {13             // 获取对应的key值,因为这里使用的是value+数字,所以直接这样获取即可14             $(".value"+i).val(localStorage.getItem("value"+i));15         }16     }17 }18 $(document).on('keyup',function(){19     localObj.localSet();20 });21 localObj.localGet();
Copy after login

2. Rendering

##3. Yoyo...just add as many as you want. How many values ​​​​are not bad, and the code is relatively simple. However, the problem comes again. I don’t want to always use the class name value+number. I already have a written class name. I can use whatever name I want. And I don’t want to create a lot of localStorage. If there are 100 inputs, do I need to create 100 of them? localStorage? ? I just want to get a localStorage record. what to do? ?

Step 5: Use json to store localStorage

1. JS code

 1 var localObj = { 2     localSet: function(){ 3         // 定一个对象,来存放键值对 4         var arr = {}; 5             // 有多少个值,就对应写多少个,名字可随便命名 6             arr.value0 = $(".value0").val(); 7             arr.value1 = $(".value1").val(); 8             arr.good = $(".good").val(); 9             arr.go = $(".go").val();10         // 将arr对象转换为string类型11         var his = JSON.stringify(arr);12         // 设置一个localStorage名字叫histroy,值为his13         localStorage.setItem("histroy",his);14     },15     localGet: function(){16         // 获取一个叫histroy的localStorage,存放在arr变量中17         var arr = localStorage.getItem("histroy");18         // 把获取来的arr转换成json格式19         var json = JSON.parse(arr);20         // 遍历Json中的数据21         for (var li in json) {22             // 由json字符串转换为json对象23             var value = eval("json['" + li +"']");24             // 把取到的对应的value值赋值给对应的li25             arr.li = value;26             // 最后一步,显示对应的value值27             $("."+li).val(value);28         }29     }30 }31 // 键盘按键弹起的时候改变localStorage的值32 $(document).on('keyup',function(){33     localObj.localSet();34 });35 // 浏览器一打开就显示存储在localStorage里面的值36 // 即记录上次输入的值37 localObj.localGet();
Copy after login
2. Rendering

##3. Wow~, not bad, go to the fifth step. Basically, our needs have been solved, but (TMD are there still problems?) Hahahaha. . .

 1) Assume that not only input needs to record the last input content, but the CheckBox also needs to record whether it was selected last time. How to solve the problem? ?

 2) Baidu Translate uses multiple arrays to store multiple contents. How to do this? ?

 

Finally: If you use sessionStorage, just replace localStorage with sessionStorage. Everything else is exactly the same! ! !

In HTML5, a new localStorage and sessionStorage features have been added. This feature is mainly used as local storage and solves the problem of insufficient cookie storage space ( The storage space of each cookie in the cookie is 4k). Generally, browsers support a size of 5M in localStorage. This will be different in localStorage and sessionStorage in different browsers.

The difference between web storage and cookies
The concept of Web Storage is similar to that of cookies. The difference is that it is designed for larger capacity storage. The size of the cookie is limited, and the cookie will be sent every time you request a new page, which wastes bandwidth. In addition, the cookie needs to specify a scope and cannot be called across domains.

In addition, Web Storage has setItem, getItem, removeItem, clear and other methods. Unlike cookies, front-end developers need to encapsulate setCookie and getCookie themselves.

But Cookies are also indispensable: Cookies are used to interact with the server and exist as part of the HTTP specification, while Web Storage is only created to "store" data locally


The above is the detailed content of Five step-by-step ways to use localStorage and sessionStorage. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Why can't localstorage successfully save data? Why can't localstorage successfully save data? Jan 03, 2024 pm 01:41 PM

Why does storing data to localstorage always fail? Need specific code examples In front-end development, we often need to store data on the browser side to improve user experience and facilitate subsequent data access. Localstorage is a technology provided by HTML5 for client-side data storage. It provides a simple way to store data and maintain data persistence after the page is refreshed or closed. However, when we use localstorage for data storage, sometimes

How to set the expiration time of localstorage items How to set the expiration time of localstorage items Jan 11, 2024 am 09:06 AM

How to set the expiration time of localstorage requires specific code examples. With the rapid development of the Internet, front-end development often requires saving data in the browser. Localstorage is a commonly used WebAPI that aims to provide a way to store data locally in the browser. However, localstorage does not provide a direct way to set the expiration time. This article will introduce how to set the expiration time of localstorage through code examples.

What are the methods to recover deleted Localstorage data? What are the methods to recover deleted Localstorage data? Jan 11, 2024 pm 12:02 PM

How to recover deleted Localstorage data? Localstorage is a technology used to store data in web pages. It is widely used in various web applications to share data between multiple pages. However, sometimes we may accidentally delete data in Localstorage, which causes us trouble. So, how to recover deleted Localstorage data? Below are specific steps and code examples. Step 1: Stop writing to Loca

Steps and precautions for using localstorage to store data Steps and precautions for using localstorage to store data Jan 11, 2024 pm 04:51 PM

Steps and precautions for using localStorage to store data This article mainly introduces how to use localStorage to store data and provides relevant code examples. LocalStorage is a way of storing data in the browser that keeps the data local to the user's computer without going through a server. The following are the steps and things to pay attention to when using localStorage to store data. Step 1: Check whether the browser supports LocalStorage

Why is localstorage unsafe? Why is localstorage unsafe? Oct 10, 2023 pm 05:38 PM

The reasons why localstorage is unsafe are unencrypted data, XSS attacks, CERF attacks, capacity limitations, etc. Detailed introduction: 1. Data is not encrypted. Localstorage is a simple key-value pair storage system. It stores data in the user's browser in clear text, which means that anyone can easily access and read the data stored in localstorage. If sensitive information is stored in localstorage, hackers or malicious users can easily obtain this information and so on.

Why can't local storage save data correctly? Why can't local storage save data correctly? Jan 03, 2024 pm 01:41 PM

Why can't localstorage save my data normally? In web development, we often need to save the user's data locally so that the data can be quickly loaded or restored the next time the user visits the website. In the browser, we can use localStorage to achieve this function. However, sometimes we find that data saved using localStorage does not work properly. So why does this happen? In understanding why localStorage

Why does localstorage fail so quickly? Why does localstorage fail so quickly? Dec 14, 2023 pm 02:55 PM

Reasons why localstorage fails quickly: 1. Browser support; 2. Storage space limit; 3. Security policy; 4. Page refresh and close; 5. JavaScript error. Detailed introduction: 1. Browser support. Different browsers may have different levels of support for LocalStorage. Some older browsers may not support LocalStorage, or there may be flaws in the implementation of LocalStorage, resulting in data failure; 2. Storage space limitations, etc. wait.

what is localstorage what is localstorage Dec 19, 2023 pm 02:07 PM

localStorage is a web API that can store and retrieve data in a web browser. It allows websites to store data in the user's local browser instead of on the server. It can be used to store many different types of data, such as user settings, preferences, shopping cart data, etc. There are different storage limits in different browsers, and there is usually a maximum storage limit. It can be used to improve the user experience of the website and provide personalized services. But you need to pay attention to privacy and so on when using localStorage.

See all articles