This time I will bring you a summary of the use of localStorage in H5. What are the precautions when using localStorage? Here are practical cases, let’s take a look.
1. What is localStorage, sessionStorage
In HTML5, a new localStorage feature has been added, this The feature is mainly used as local storage, which 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 is different in different browsers. localStorage will be different.
2. Advantages and limitations of localStorage
Advantages of localStorage
1. LocalStorage expansion Overcoming the 4K limit of cookies
2. LocalStorage will be able to store the first requested data directly locally. This is equivalent to a 5M database for the front-end page. Compared with cookies, it can save bandwidth. However, this is only supported in higher version browsers.
Limitations of localStorage
1. The sizes of browsers are not uniform, and in IE8 or above Only the IE version supports the attribute of localStorage
2. Currently, all browsers limit the value type of localStorage to the string type. This is required for our daily common JSON object types. Some conversions
3. LocalStorage is not readable in the browser's privacy mode
4. LocalStorage essentially reads the string. If stored If there is a lot of content, it will consume memory space and cause the page to become stuck.
5. LocalStorage cannot be crawled by crawlers.
The only difference between localStorage and sessionStorage is that localStorage is a permanent storage, while sessionStorage When the session ends, the key-value pairs in sessionStorage will be cleared
Here we use localStorage to analyze
3. The use of localStorage
LocalStorage browser support:
A special statement here is that if you are using IE browser, then UserData is required As storage, the main explanation here is the content of localStorage, so userData will not be explained too much. In the blogger's personal opinion, there is no need to learn the use of UserData, because the current IE6/IE7 is obsolete. position, and many page development today will involve emerging technologies such as Html5\CSS3, so we generally will not make it compatible when using the above
First of all, when using localStorage, we need to judge Whether the browser supports the localStorage attribute
if(!window.localStorage){ alert("浏览器支持localstorage"); return false; }else{ //主逻辑业务 }
There are three ways to write localStorage. Here we will introduce them one by one
if(!window.localStorage){ alert("浏览器支持localstorage"); return false; }else{ var storage=window.localStorage; //写入a字段 storage["a"]=1; //写入b字段 storage.a=1; //写入c字段 storage.setItem("c",3); console.log(typeof storage["a"]); console.log(typeof storage["b"]); console.log(typeof storage["c"]); }
The results after running are as follows:
It should be noted here that the use of localStorage also follows the same-origin policy, so different websites cannot directly share the same localStorage
The final result printed on the console is:
I don’t know if readers have noticed that what was just stored was of type int, but it was printed as type of string. This is related to the characteristics of localStorage itself. LocalStorage only supports storage of string type.
Reading of localStorage
if(!window.localStorage){ alert("浏览器支持localstorage"); }else{ var storage=window.localStorage; //写入a字段 storage["a"]=1; //写入b字段 storage.a=1; //写入c字段 storage.setItem("c",3); console.log(typeof storage["a"]); console.log(typeof storage["b"]); console.log(typeof storage["c"]); //第一种方法读取 var a=storage.a; console.log(a); //第二种方法读取 var b=storage["b"]; console.log(b); //第三种方法读取 var c=storage.getItem("c"); console.log(c); }
There are three ways to read localStorage, among which the two officially recommended methods are getItem\setItem to save it. Take, don't ask me why, because I don't know this either
I said before that localStorage is equivalent to a front-end database. The database mainly consists of four steps of adding, deleting, checking and modifying. The reading here and writing are equivalent to the two steps of adding and checking.
Let’s talk about the two steps of deleting and modifying localStorage.
It is easier to understand this step. The idea is Just like re-changing the value of a global variable, here we will take an example to briefly explain
if(!window.localStorage){ alert("浏览器支持localstorage"); }else{ var storage=window.localStorage; //写入a字段 storage["a"]=1; //写入b字段 storage.b=1; //写入c字段 storage.setItem("c",3); console.log(storage.a); // console.log(typeof storage["a"]); // console.log(typeof storage["b"]); // console.log(typeof storage["c"]); /*分割线*/ storage.a=4; console.log(storage.a); }
On the console, we can see that the a key has been changed to 4
localStorage的删除
1、将localStorage的所有内容清除
var storage=window.localStorage; storage.a=1; storage.setItem("c",3); console.log(storage); storage.clear(); console.log(storage);
2、 将localStorage中的某个键值对删除
var storage=window.localStorage; storage.a=1; storage.setItem("c",3); console.log(storage); storage.removeItem("a"); console.log(storage.a);
控制台查看结果
localStorage的键获取
var storage=window.localStorage; storage.a=1; storage.setItem("c",3); for(var i=0;i<storage.length><p style="text-align: left;">使用key()方法,向其中出入索引即可获取对应的键</p> <p style="text-align: left;"><strong><span style="color:#ff0000">四、localStorage其他注意事项</span></strong></p> <p style="text-align: left;"> 一般我们会将JSON存入localStorage中,但是在localStorage会自动将localStorage转换成为字符串形式</p> <p style="text-align: left;">这个时候我们可以使用JSON.stringify()这个方法,来将JSON转换成为JSON字符串</p> <p style="text-align: left;">示例:</p> <pre class="brush:php;toolbar:false">if(!window.localStorage){ alert("浏览器支持localstorage"); }else{ var storage=window.localStorage; var data={ name:'xiecanyong', sex:'man', hobby:'program' }; var d=JSON.stringify(data); storage.setItem("data",d); console.log(storage.data); }
读取之后要将JSON字符串转换成为JSON对象,使用JSON.parse()方法
var storage=window.localStorage; var data={ name:'xiecanyong', sex:'man', hobby:'program' }; var d=JSON.stringify(data); storage.setItem("data",d); //将JSON字符串转换成为JSON对象输出 var json=storage.getItem("data"); var jsonObj=JSON.parse(json); console.log(typeof jsonObj);
打印出来是Object对象
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Summary of H5 localStorage usage. For more information, please follow other related articles on the PHP Chinese website!

HTML5audioandvideoelementsenhancefunctionalityandaccessibilitythroughspecificattributes.1)The'controls'attributeaddsstandardplaybackcontrols,while'aria-label'improvesscreenreaderaccessibility.2)The'poster'attributeenhancesvideouserexperience,and'trac

MicrodatainHTML5enhancesSEOanduserexperiencebyprovidingstructureddatatosearchengines.1)Useitemscope,itemtype,anditempropattributestomarkupcontentlikeproductsorevents.2)TestmicrodatawithtoolslikeGoogle'sStructuredDataTestingTool.3)ConsiderusingJSON-LD

HTML5introducesnewinputtypesthatenhanceuserexperience,simplifydevelopment,andimproveaccessibility.1)automaticallyvalidatesemailformat.2)optimizesformobilewithanumerickeypad.3)andsimplifydateandtimeinputs,reducingtheneedforcustomsolutions.

H5 is HTML5, the fifth version of HTML. HTML5 improves the expressiveness and interactivity of web pages, introduces new features such as semantic tags, multimedia support, offline storage and Canvas drawing, and promotes the development of Web technology.

Accessibility and compliance with network standards are essential to the website. 1) Accessibility ensures that all users have equal access to the website, 2) Network standards follow to improve accessibility and consistency of the website, 3) Accessibility requires the use of semantic HTML, keyboard navigation, color contrast and alternative text, 4) Following these principles is not only a moral and legal requirement, but also amplifying user base.

The H5 tag in HTML is a fifth-level title that is used to tag smaller titles or sub-titles. 1) The H5 tag helps refine content hierarchy and improve readability and SEO. 2) Combined with CSS, you can customize the style to enhance the visual effect. 3) Use H5 tags reasonably to avoid abuse and ensure the logical content structure.

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
