随着互联网的快速发展,基于网页的应用越来越普遍,同时也变得越来越复杂,为了满足各种各样的需求,会经常性在本地存储大量的数据,HTML5规范提出了相关解决方案。
sessionStorage.setItem(key, value);
sessionStorage.getItem(key);
sessionStorage.removeItem(key);
sessionStorage.clear();
<!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>
<input type="text">
<button class="set">存储数据</button>
<button class="get">获取数据</button>
<button class="remove">删除数据</button>
<button class="del">清空所有数据</button>
<script>
var ipt = document.querySelector('input');
var set = document.querySelector('.set');
var get = document.querySelector('.get');
var remove = document.querySelector('.remove');
var del = document.querySelector('del')
set.addEventListener('click', function () {
//当我们点击了之后就可以把表单里面的值存储起来
var val = ipt.value;
sessionStorage.setItem('uname', val);
});
get.addEventListener('click', function () {
console.log(sessionStorage.getItem('uname'));
});
remove.addEventListener('click', function () {
sessionStorage.removeItem('uname');
});
del.addEventListener('click', function () {
sessionStorage.clear();
});
</script>
</body>
</html>
localStorage.setItem(key, value);
localStorage.getItem(key);
localStorage.removeItem(key);
localStorage.clear();
<!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>
<input type="text">
<button class="set">存储数据</button>
<button class="get">获取数据</button>
<button class="remove">删除数据</button>
<button class="del">清空所有数据</button>
<script>
var ipt = document.querySelector('input');
var set = document.querySelector('.set');
var get = document.querySelector('.get');
var remove = document.querySelector('.remove');
var del = document.querySelector('del')
set.addEventListener('click', function () {
//当我们点击了之后就可以把表单里面的值存储起来
var val = ipt.value;
localStorage.setItem('uname', val);
});
get.addEventListener('click', function () {
console.log(localStorage.getItem('uname'));
});
remove.addEventListener('click', function () {
localStorage.removeItem('uname');
});
del.addEventListener('click', function () {
localStorage.clear();
});
</script>
</body>
</html>