HTML5 web

HTML5 web storage , a better local storage method than cookies . Use HTML5 to store user browsing data locally.

Earlier , local storage used cookies . But web storage needs to be more secure and faster . These data will not be saved on the server, but these data are only used for user requests for website data . It can also store large amounts of data without affecting the performance of the website. The data exists in key / value pairs , and the data of the web page is only allowed to be accessed and used by the web page.

(1), localStorage object

It is used to save the data of the entire website for a long time. The saved data has no expiration time until it is manually removed. The data stored by the localStorage object has no time limit. The data is still available the next day, week or year.

Regardless of localStorage or sessionStorage , the available APIs are the same, and the commonly used ones are as follows (take localStorage as an example):

Save data: localStorage.setItem(key,value);

Read data: localStorage.getItem(key);

Delete a single item: localStorage.removeItem(key);

Delete all data: localStorage.clear();

Get the key of an index : localStorage.key(index);

The example below shows the number of times a user clicks a button.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
    <button id="save">保存数据</button>
    <button id="get">读取数据</button>
    <button id="remove">删除单个数据</button>
    <button id="clear">删除所有数据</button>
    <button id="index">获取key值</button>


</body>
<script>

  console.log(localStorage);
  // 一直在浏览器本地存储,除非手动清除掉
  console.log(localStorage.constructor);
  // 1、保存数据:localStorage.setItem(key,value);
  document.getElementById('save').onclick=function(){
    localStorage.setItem('name','小花')
    localStorage.setItem('age',18)
    localStorage.setItem('A',11)
    localStorage.setItem('B',12)
    localStorage.setItem('C',13)
    localStorage.setItem('get11',13)

    console.log(localStorage);
  }
  // 2、读取数据:localStorage.getItem(key);
  console.log(localStorage.getItem('age'));
  console.log(localStorage.getItem('name'));
  // 3、删除单个数据:localStorage.removeItem(key);
  document.getElementById('remove').onclick=function(){
    localStorage.removeItem('name')
    // console.log(localStorage);
    localStorage.removeItem('age')
    console.log(localStorage);

  }
  // 4、删除所有数据:localStorage.clear();
  document.getElementById('clear').onclick=function(){
    localStorage.clear()
    console.log(localStorage);
  }
  // 5、得到某个索引的key:localStorage.key(index);
  document.getElementById('index').onclick=function(){
    console.log(localStorage.key(0));
  }
</script>
</html>

Guess you like

Origin blog.csdn.net/weixin_47619284/article/details/127044068