<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Examples</title>
<style type="text/css">
html,body,div,ul,li,span{
margin: 0;
padding-top: 0;
}
ul,li{
list-style: none;
}
#bg{
width: 500px;
height: 400px;
background-color: pink;
border:1px solid purple;
margin: 100px auto;
}
.tap input:first-of-type{
width: 400px;
height: 50px;
border:1px solid darkgreen;
border-radius: 10px;
margin:50px 0 0 20px;
}
.tap input:last-of-type{
width: 50px;
height: 50px;
border:1px solid black;
border-radius: 8px;
background-color: #cccccc;
font-size: 14px;
color: blue;
}
.con{
margin:30px 0 0 40px;
width: 400px;
height: 200px;
border:1px solid black;
background-color: #ffffff;
}
.clear{
width: 70px;
border-radius: 8px;
background-color: #cccccc;
margin: 20px 0 0 40px;
}
</style>
</head>
<body>
<div id="bg">
<div class="tap">
<input type="text" name="">
<input type="button" value="發(fā)表" onclick=save()>
</div>
<div class="con">
<ul></ul>
</div>
<div class="clear">
<input type="button" value="清空所有" onclick=clearAll()>
</div>
</div>
</body>
<script type="text/javascript">
var input = document.querySelector("input[type=text]");
var ul = document.querySelector("ul");
// 存儲
function save() {
if(window.localStorage){
if(input.value!= ""){
// length 獲取localStorage 里存儲的容量
// var length = window.localStorage.length;
var obj = {
value : input.value,
date : (new Date()).toLocaleString()
}
// 存儲 input的值 input.value 轉(zhuǎn)成 json 字符串對象
window.localStorage.setItem(obj.date, JSON.stringify(obj));
// 將字符串li 拼接進 ul里
ul.appendChild(addMessage(obj));
// 發(fā)送完清空
input.value = "";
}
}
}
// 發(fā)送方法
function addMessage(obj) {
// 創(chuàng)建li
var li = document.createElement("li");
li._index = obj.date;
//拼接字符串
var str= "";
str += "<span>"+ obj.value + "</span>";
str += "<span>"+ obj.date + "</span>";
str += "<button >"+ "刪除" + "</button>";
li.innerHTML = str;
return li;
}
readStorage();
function readStorage() {
// 先判斷
if(window.localStorage){
// 文檔事件 集中 dom 事件 集中插入文檔 減少dom操作
var frg = document.createDocumentFragment();
for(var key in window.localStorage){
var obj = JSON.parse(window.localStorage.getItem(key));
if(obj){
frg.appendChild(addMessage(obj));
}
}
ul.appendChild(frg);
}else{
alert("沒找到相關(guān)信息")
}
}
function clearAll() {
// clear清除所有
window.localStorage.clear();
ul.innerHTML = "";
}
// 事件委托代理 清空 nodeName nodeValue nodeType 的屬性名都為大寫
ul.addEventListener("click",function (e) {
if(e.target.nodeName == "BUTTON"){
ul.removeChild(e.target.parentNode);
window.localStorage.removeItem(e.target.parentNode._index);
}
})
</script>
</html>