Home > Web Front-end > H5 Tutorial > Detailed explanation of local storage usage of H5's LocalStorage

Detailed explanation of local storage usage of H5's LocalStorage

php中世界最好的语言
Release: 2018-03-27 09:20:30
Original
2939 people have browsed it

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 and

sessionStorage. You can clearly identify the difference between the two from their names. The former always exists locally, while the latter only accompanies the session. , the window disappears once it is closed. The usage of the two is exactly the same. Here we take localStorage as an example.

if(window.localStorage){
 alert('This browser supports localStorage');
}else{
 alert('This browser does NOT support localStorage');
}
Copy after login
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的值
Copy after login
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;i++){
  //key(i)获得相应的键,再用getItem()方法获得对应的值
  document.write(storage.key(i)+ " : " + storage.getItem(storage.key(i)) + "<br>");
 }
}
Copy after login
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();
Copy after login
Keep refreshing and you will see the number rising little by little, as shown in the figure below:


It should be noted that HTML5 local storage can only store strings , any format will be automatically converted to a string when stored, so when reading, you need to perform type conversion yourself. This is why parseInt must be used in the previous code.

In addition, sometimes a strange QUOTA_EXCEEDED_ERR error occurs when setting setItem() on iPhone/iPad. In this case, removeItem() is usually OK before settingItem.

HTML5’s local storage also provides a storage event, which can monitor changes in key-value pairs. The usage method is as follows:

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();
}
Copy after login
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的值:


You have viewed this page 0  time(s).

<script> var storage = window.localStorage; if (!storage.getItem(&quot;pageLoadCount&quot;)) storage.setItem(&quot;pageLoadCount&quot;,0); storage.pageLoadCount = parseInt(storage.getItem(&quot;pageLoadCount&quot;)) + 1;//必须格式转换 document.getElementByIdx_x(&quot;count&quot;).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>
Copy after login

测试发现,目前浏览器对这个支持不太好,仅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"));
Copy after login


 

JSON对象在支持localStorage的浏览器上基本都支持,需要注意的是IE8,它支持JSON,但如果添加了如下的兼容模式代码,切到IE7模式就不行了(此时依然支持localStorage,虽然显示window.localStorage是[object],而不是之前的[object Storage],但测试发现getItem()、setItem()等均能使用)。

<meta content="IE=7" http-equiv="X-UA-Compatible"/>
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

<a href="//m.sbmmt.com/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!

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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template