Home > Web Front-end > H5 Tutorial > body text

How H5's LocalStorage stores refresh values ​​locally

php中世界最好的语言
Release: 2018-03-26 14:37:57
Original
3094 people have browsed it

This time I will show you how H5's LocalStorage stores refresh values ​​locally. What are the precautions for H5's LocalStorage to store refresh values ​​locally? Here is a practical case, let's take a look.

The biggest difference between the two storage technologies of H5 is life cycle.

1. localStorage is local storage, and the storage period is not limited;

2. sessionStorage session storage, the data will be lost when the page is closed lost.

Usage:

localStorage.setItem("key", "value") //Storage

localStorage.getItem(key)//Get the value by key

localStorage.valueOf()//Get all values

localStorage.removeItem("key")//Delete a single value, Pay attention to the quotation marks

localStorage.clear()//Delete all data

localStorage.length//Get the number of data

localStorage.key(N)//Get the Nth The key value of each data

Note: localStorage and sessionStorage are the same as above, and the usage methods are the same

Commonly used summaries:

localStorage.key = 1;//Set storage, named key, value 1

localStorage.removeItem("key");//Remove storage key, remember to add quotes

The following is a practical example for testing:

to save the entered text content locally, so that after closing the browser and reopening it, the previously entered content is still there (common in DingTalk on mobile phones) Field entry for leave and other fields in the log).

First of all, create a text area on the page. The following is jQuery:

if(!localStorage.getItem("text"))  //window对象的话,前面的window省略了哦
    localStorage.setItem("text","");  //这里先判断一下,做空白存储,否则返回 NULL 显示出来体验不好,这里的if大括号省去了
    localStorage.text = localStorage.getItem("text");  //取值
    $("textarea").html(localStorage.text);  //显示
    $("textarea").keyup(function(){  //这里有很多,比如blur, change, keydown, 还有做个定时器也行,实用于多字段存储
        localStorage.setItem("text",$(this).val());  //重新存储
    });
Copy after login

The above can implement a practical small function, reflecting the H5 local storage or Very useful. Of course, if there are many fields, there is a JSON method provided! See the following, downloaded from the Internet

<script type="text/javascript">
    if(window.sessionStorage){
        alert('ok');
    }else{
        alert('fail');
    }
    // 设置值
    sessionStorage.setItem('key_a', 1);
    // 取值
    var key_a = sessionStorage.getItem('key_a');
    console.log(key_a);
    // 删除
    sessionStorage.removeItem('key_a');
    console.log(sessionStorage.getItem('key_a'));// null
    sessionStorage.setItem('key_b', 1);
    sessionStorage.setItem('key_c', 2);
    // 清除所有键值
    sessionStorage.clear();
    console.log(sessionStorage.key_b);
    console.log(sessionStorage.key_c);
    console.log('==================');
    // 设置值和取值也可以使用.符号,类似于取对象属性
    // 设置值
    sessionStorage.key_d = 12;
    // 取值
    var key_d = sessionStorage.key_d;
    console.log(key_d);
    // 有个小区别,如果这个key没有了。一个返回值undefined,一个是null
    console.log(sessionStorage.key_null);// undefined
    console.log(sessionStorage.getItem('key_null'));// null
    console.log('==========简单演示一个存放对象的例子========');
    var obj = {
        a : 12,
        b : [1,2,3,4,5],
        c : {
            x : 'a',
            y : ['bb', 12, 'cc', {a:1,b:2}],
            z : 1333
        }
    };
    sessionStorage.setItem('page', JSON.stringify(obj));
    // 取值
    var page = JSON.parse(sessionStorage.getItem('page'));
    console.log(page);
    // 遍历下数组
    for(var i=0;i< page.b.length;i++){
        console.log(page.b[i]);
    }
    // 遍历对象,通常用in
    for(var j in page.c){
        console.log(page.c[j])
    }
    // 删除key
    sessionStorage.removeItem(&#39;page&#39;);
</script>
Copy after login

Example: Counter, refresh the page, you can see the effect:

<p id="test"></p>
<script>
var storage = window.localStorage;
if (!storage.getItem("pageLoadCount"))
storage.setItem("pageLoadCount",0);
storage.pageLoadCount = parseInt(storage.getItem("pageLoadCount")) + 1;//必须格式转换
document.getElementById("test").innerHTML = storage.pageLoadCount;
//showStorage();
</script>
Copy after login

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.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the storage method of H5

##zepto realizes seamless scrolling up and down on the mobile terminal

The above is the detailed content of How H5's LocalStorage stores refresh values ​​locally. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!