<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{margin:0;padding:0;}
div{width:500px;
height:auto!important;
min-height: 800px;
height:800px;
margin: 50px auto;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#txt{
width:440px;
height:169px;
}
#list{
width:400px;
height:auto!important;
min-height:400px;
height:400px;
border:1px solid #ccc;
list-style: none;
}
li{
border-bottom: 1px solid #ccc;
overflow: hidden;
margin-bottom: 8px;
height:45px;}
p{
font-size:12px;
color:#f5e79e;
float:right;}
b{
font-size:20px;
color:red;}
span{
margin-bottom: 5px;
}
</style>
</head>
<body>
<div>
输入你的名字:<input type="text" id="Name">
<textarea name="" id="txt" cols="30" rows="10">
</textarea><br>
<input type="button" value="添加" id="add">
<input type="button" value="删除" id="clear">
<ul id="list"></ul>
</div>
</body>
<script>
var txt=document.getElementById("txt");
var add=document.getElementById("add");
var clear=document.getElementById("clear");
var list=document.getElementById("list");
var Name=document.getElementById("Name");
//Name.value+txt.value
data();
add.onclick=function(){
var time=new Date();
var val=Name.value+"|"+txt.value;//string
console.log(val);
localStorage.setItem(time,val);
console.log(localStorage.getItem(time));
data();
};
clear.onclick=function(){
localStorage.clear();
list.innerHTML="";
txt.value="";
};
function data(){
var str="";
//先存取数据
console.log(localStorage.length);//3
for(var i=0;i<localStorage.length;i++){
var keys=localStorage.key(i);//获取循环下所有key值;
console.log(keys);
//取到value
var value=localStorage.getItem(keys);//value Name.value+"|"+txt.value;
if(value.split("|")[0]==""){
str+="<li><b>匿名人</b>:<span>"+value.split("|")[1]+"</span><p>"+keys+"</p></li>"
}else{
str+="<li><b>"+value.split("|")[0]+"</b>:<span>"+value.split("|")[1]+"</span><p>"+keys+"</p></li>"
}
}
list.innerHTML=str;
var lis=list.getElementsByTagName("li");
for(var i=0;i<lis.length;i++){
lis[i].index=i;
lis[i].ondblclick=function(){
list.removeChild(this);
var ks=localStorage.key(this.index);
localStorage.removeItem(ks);
}
}
}
</script>
</html>