<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
//localStorage 存储数据
function set(){
//获取数据
var inputKey = document.querySelector("#inputKey"); //key
var inputValue = document.querySelector("#inputValue"); //value
if(inputKey.value == ''){
alert('key 是空的');
return false;
}
if(inputValue.value == ''){
alert('value 是空的');
return false;
}
//localStorage.setItem( 键(key) , 值(value) );
localStorage.setItem( inputKey.value , inputValue.value);
alert('保存成功');
}
//localStorage 读取数据
function get(){
//获取数据
var inputKey = document.querySelector("#inputKey"); //key
if(inputKey.value == ''){
alert('key 是空的');
return false;
}
//localStorage.getItem( 键(key) );
var value = localStorage.getItem(inputKey.value);
var input = document.querySelector("#inputValue");
//判断是否有 localStorage 存储
var content = checkAllData(inputKey.value);
if(content){
input.value = value;
}else{
alert('没有' + inputKey.value);
}
}
//localStorage 删除数据
function removeItem(){
//获取数据
var inputKey = document.querySelector("#inputKey"); //key
if(inputKey.value == ''){
alert('key 是空的');
return false;
}
//判断是否有 localStorage 存储
var content = checkAllData(inputKey.value);
if(content){
//localStorage.removeItem( 键(key) );
var value = localStorage.removeItem(inputKey.value);
alert('清除' + inputKey.value + '成功');
}else{
alert('没有' + inputKey.value);
}
}
//判断是否有 localStorage 存储
function checkAllData( inputKey ){
//循环 localStorage 所有缓存数据
for(var i = 0; i < localStorage.length; i++){
var key = localStorage.key(i);
var value = localStorage.getItem(key);
if(key == inputKey){
var content = true;
continue;
}
}
return content;
}
//localStorage 删除全部数据
function clearAll(){
//判断是否有 localStorage 存储
var content = checkAllData(inputKey.value);
if(content){
localStorage.clear();
alert('清空完成');
}else{
alert('没有数据');
}
}
</script>
</head>
<body>
key: <input type="text" id="inputKey" /><br />
value: <input type="text" id="inputValue" /><br />
<button onclick="set()">保存</button>
<button onclick="get()">获取</button>
<button onclick="removeItem()">清除单个</button>
<button onclick="clearAll()">清空</button>
</body>
</html>