前言:今天写了个小练习,把这几天看的东西巩固一下,在这个程序中用到了localStorage存储和json串的转换。
下面是具体的实现代码:
(1)首先判断是否存在用户,从而显示相应的界面
function isUser() { var storage = window.localStorage; if (storage.user != undefined) { document.getElementById("showmess").style.display = "block"; document.getElementById("fillmess").style.display = "none"; } else { document.getElementById("showmess").style.display = "none"; document.getElementById("fillmess").style.display = "block"; } }
(2)存储用户信息
var pic; //全局变量存储图片信息 /*从本地电脑获得图片*/ function add_files(files) { if (files.length) { var file = files[0]; var reader = new FileReader(); reader.onload = function(e) { document.getElementById("userpic").src = e.target.result; pic = e.target.result; } reader.readAsDataURL(file); } } function saveUserMess() { var name = document.getElementById("username").value; if (name != "") { var storage = window.localStorage; var jsonObj = { name:name, icon:pic }; var user = JSON.stringify(jsonObj); storage.setItem("user",user); } else { alert("昵称不为空"); } }
(3)用户输入便签内容,并保存
function save_diary() { var headle = document.getElementById("headle").value; var cont = document.getElementById("diary").value; if (headle != "" && cont != "") { var storage = window.localStorage; if (storage.diary != undefined) { var diary = storage.getItem("diary"); var jsonObj = JSON.parse(diary); var diaryItem = { headle:headle, diary:cont, date:new Date() }; jsonObj.push(diaryItem); var data = JSON.stringify(jsonObj); storage.setItem("diary",data); } else { var jsonObj = [{ headle:headle, diary:cont, date:new Date() }]; var diary = JSON.stringify(jsonObj); storage.setItem("diary",diary); } } else { alert("标题和内容不为空哦"); } }
(4)将用户便签信息显示在见面
function showDiary() { var storage = window.localStorage; var mess = JSON.parse(storage.user); if (storage.diary != undefined) { var json = JSON.parse(storage.diary); var div_id = document.getElementById("diarymess"); for (var i = 0; i < json.length; i++) { div_id.innerHTML+='<div><button'+'type="button"><div><img src='https://www.jb51.net/+mess.icon+'><br><font>'+mess.name+'</font></div><div><h2>'+json[i].headle+'</h2><font>'+json[i].date+'</font></div><span>'+'</span></button><p>'+json[i].diary+'</p><div>'; } } }