一、什么是本地存储?
- 通过本地存储(Local Storage),web 应用程序能够在用户浏览器中对数据进行本地的存储。
- 在 HTML5 之前,应用程序数据只能存储在 cookie
中,包括每个服务器请求。本地存储则更安全,并且可在不影响网站性能的前提下将大量数据存储于本地。 - 与 cookie 不同,存储限制要大得多(至少5MB),并且信息不会被传输到服务器。
二、本地存储使用方法
下面代代码片段通过localstrorage
var tool=localStorage.getItem('list') || [];
tool=JSON.parse(tool);//字符串转化为数组
localStorage.setItem('list',JSON.stringify(tool));
-
名字叫做list,JSON.stringif是将数组转化为字符串
-
JSON.parse(tool); // 字符串转化为数组
在控制台演示一下
下面用一个案例演示一下
功能说明:
- 点击添加的时候,创建一个li并且填充内容
- 点击所在的 li 项删除
- 重点就是刷新网页的时候数据能保存
代码如下
<style>
*{
margin: 0;
padding: 0;
list-style: none;
}
.bs .i1{
width: 200px;
height: 30px;
}
ul li{
width: 200px;
height:30px;
border: 1px solid red;
margin-top: 10px;
}
.sc{
width: 200px;
height: 20px;
border: 1px solid red;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="bs">
<input class="i1" type="text"/>
<input class="add" type="button"value="添加"/>
</div>
<ul class="u">
<li>1</li>
<li>2</li>
</ul>
<script>
var inputtext=document.querySelector('.i1');
var addtext=document.querySelector('.add');
var utext=document.querySelector('.u');
var tool=localStorage.getItem('list') || [];
tool=JSON.parse(tool);//字符串转化为数组
//遍历
tool.forEach(function(value){
var newli=document.createElement('li');
newli.className='sc';
newli.innerHTML=value;
utext.appendChild(newli);
inputtext.value='';
});
//添加
addtext.onclick=function(){
var newli=document.createElement('li');
newli.className='sc';
newli.innerHTML=inputtext.value;
if( newli.innerHTML == ''){
alert("内容不能为空,请输入内容");
}
utext.appendChild(newli);
tool.push(inputtext.value);
inputtext.value='';
localStorage.setItem('list',JSON.stringify(tool));//把数组变成字符串
}
utext.onclick=function(event){
if(event.target.tagName === "LI"){
event.target.remove();
}
tool.forEach(function(value,index){
if(value === event.target.innerText){
tool.splice(index,1);
}
});
localStorage.setItem('list',JSON.stringify(tool));//把数组变成字符串
}
</script>