在以前,我们想要存储一些数据,并且只是在前端使用,服务端并不会使用,我们只能存在cookie里,但是cookie会跟随请求头在客户端和服务端之间来回传递,而且cookie还有一些缺点,H5提供了webStorage的API用来做客户端的数据存储
cookie与webStorage的区别 webStorage包含的存储方式 localStorage和sessionStorage 的使用方法(API)localStorage和sessionStorage的使用方法一样
增删改查
增/改: localStorage.setItem(key,value)/ localStorage.a = 1
查: length;key方法(index)得到对应的key getItem(key)/localStorage.a
删: removeItem(key)
清空: clear()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<style>
.panel-body input.form-control{
width: 200px;
}
</style>
<body>
<div class="container">
<div class="panel panel-primary insert">
<div class="panel-heading">
增加
</div>
<div class="panel-body">
<label for="">key:</label>
<input type="text" id="key" class="form-control">
<label for="">value:</label>
<input type="text" id="value" class="form-control">
<button onclick="save()">save</button>
</div>
</div>
<div class="panel panel-primary select">
<div class="panel-heading">
key-value-list:
</div>
<div class="panel-body">
<button onclick="select()" class="btn btn-success">select</button>