Detailed explanation of local storage usage of H5's LocalStorage
This time I will bring you a detailed explanation of the use of H5's LocalStorage local storage. What are the precautions when using LocalStorage local storage? Here are practical cases, let's take a look.
Speaking of local storage, this thing has really gone through a lot of hard work to get to the point of HTML5. The previous history is roughly as shown in the figure below:
Everyone knows about the earliest Cookies. The main problem is that they are too small, about 4KB, and IE6 only supports 20 cookies per domain name, which is too few. The advantage is that everyone supports it, and the support is quite good. Those users who disabled cookies a long time ago have gradually disappeared, just like the users who disabled javascript in the past no longer exist.
userData is something from IE, garbage. The most commonly used one now is Flash. The space is 25 times that of Cookie, which is basically enough. Then Google launched Gears. Although there are no restrictions, the unpleasant part is that additional plug-ins must be installed (I have not studied it in detail). With HTML5, these have been unified. The official recommendation is 5MB for each website, which is very large. Just save some strings, which is enough. What is strange is that all supported browsers currently use 5MB. Although some browsers allow users to set it, for web page creators, it is more appropriate to consider 5MB in the current situation.
The support situation is as shown above. IE has supported it since 8.0, which is very unexpected. However, it should be noted that when testing IE and Firefox, you need to upload the file to the server (or localhost). Directly clicking on the local HTML file will not work.
The first thing is to check whether the browser supports local storage. In HTML5, local storage is a window attribute, including localStorage andif(window.localStorage){ alert('This browser supports localStorage'); }else{ alert('This browser does NOT support localStorage'); }The way to store data is to directly add a property to window.localStorage, such as: window.localStorage.a or window.localStorage["a"]. Its reading, writing, and deletion operation methods are very simple and exist in the form of key-value pairs, as follows:
localStorage.a = 3;//设置a为"3" localStorage["a"] = "sfsf";//设置a为"sfsf",覆盖上面的值 localStorage.setItem("b","isaac");//设置b为"isaac" var a1 = localStorage["a"];//获取a的值 var a2 = localStorage.a;//获取a的值 var b = localStorage.getItem("b");//获取b的值 localStorage.removeItem("c");//清除c的值The most recommended ones here are naturally getItem() and setItem() to clear the key value Use removeItem() on . If you want to clear all key-value pairs at once, you can use clear(). In addition, HTML5 also provides a key() method, which can be used when you don’t know what key values there are, as follows:
var storage = window.localStorage; function showStorage(){ for(var i=0;i<storage.length>"); } }</storage.length>Write the simplest counter that uses local storage:
var storage = window.localStorage; if (!storage.getItem("pageLoadCount")) storage.setItem("pageLoadCount",0); storage.pageLoadCount = parseInt(storage.getItem("pageLoadCount")) + 1;//必须格式转换 document.getElementByIdx_x("count").innerHTML = storage.pageLoadCount; showStorage();Keep refreshing and you will see the number rising little by little, as shown in the figure below:
if(window.addEventListener){ window.addEventListener("storage",handle_storage,false); }else if(window.attachEvent){ window.attachEvent("onstorage",handle_storage); } function handle_storage(e){ if(!e){e=window.event;} //showStorage(); }For the event variable e, it is a StorageEvent object, providing With some practical attributes, you can observe the changes of key-value pairs very well, as shown in the following table:
Property |
Type |
Description |
key |
String |
The named key that was added, removed, or moddified |
oldValue |
Any |
The previous value(now overwritten), or null if a new item was added |
newValue |
Any |
The new value, or null if an item was added |
url/uri |
String |
The page that called the method that triggered this change |
这里添加两个键值对a和b,并增加一个按钮。给a设置固定的值,当点击按钮时,修改b的值:
<p>You have viewed this page <span>0</span> time(s).</p> <p><input></p> <script> var storage = window.localStorage; if (!storage.getItem("pageLoadCount")) storage.setItem("pageLoadCount",0); storage.pageLoadCount = parseInt(storage.getItem("pageLoadCount")) + 1;//必须格式转换 document.getElementByIdx_x("count").innerHTML = storage.pageLoadCount; showStorage(); if(window.addEventListener){ window.addEventListener("storage",handle_storage,false); }else if(window.attachEvent){ window.attachEvent("onstorage",handle_storage); } function handle_storage(e){ if(!e){e=window.event;} showObject(e); } function showObject(obj){ //递归显示object if(!obj){return;} for(var i in obj){ if(typeof(obj[i])!="object" || obj[i]==null){ document.write(i + " : " + obj[i] + "<br/>"); }else{ document.write(i + " : object" + "<br/>"); } } } storage.setItem("a",5); function changeS(){ //修改一个键值,测试storage事件 if(!storage.getItem("b")){storage.setItem("b",0);} storage.setItem('b',parseInt(storage.getItem('b'))+1); } function showStorage(){ //循环显示localStorage里的键值对 for(var i=0;i<storage.length;i++){ //key(i)获得相应的键,再用getItem()方法获得对应的值 document.write(storage.key(i)+ " : " + storage.getItem(storage.key(i)) + "<br>"); } } </script>
测试发现,目前浏览器对这个支持不太好,仅iPad和Firefox支持,而且Firefox支持得乱糟糟,e对象根本没有那些属性。iPad支持非常好,用的是e.uri(不是e.url),台式机上的Safari不行,诡异。
目前浏览器都带有很好的开发者调试功能,下面分别是Chrome和Firefox的调试工具查看LocalStorage:
另外,目前javascript使用非常多的json格式,如果希望存储在本地,可以直接调用JSON.stringify()将其转为字符串。读取出来后调用JSON.parse()将字符串转为json格式,如下所示:
var details = {author:"isaac","description":"fresheggs","rating":100}; storage.setItem("details",JSON.stringify(details)); details = JSON.parse(storage.getItem("details"));
JSON对象在支持localStorage的浏览器上基本都支持,需要注意的是IE8,它支持JSON,但如果添加了如下的兼容模式代码,切到IE7模式就不行了(此时依然支持localStorage,虽然显示window.localStorage是[object],而不是之前的[object Storage],但测试发现getItem()、setItem()等均能使用)。
<meta content="IE=7" http-equiv="X-UA-Compatible"/>
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
<a href="http://www.php.cn/html5-tutorial-390148.html" target="_blank">基于HTML5陀螺仪实现移动动画效果</a><br>
怎样用H5计算手机摇动次数
The above is the detailed content of Detailed explanation of local storage usage of H5's LocalStorage. For more information, please follow other related articles on the PHP Chinese website!

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.


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

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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
