前言:今天寫了個小練習,把這幾天看的東西鞏固一下,在這個程序中用到了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 class="btn btn-success"'+'type="button" id="dropdownMenu" onclick="show(this)"><div class="col-md-4"><img src='+mess.icon+' class="img-circle size" id="userpic"><br><font style="text-align:center">'+mess.name+'</font></div><div class="col-md-8"><h2>'+json[i].headle+'</h2><font>'+json[i].date+'</font></div><span class="caret" style="margin-top:50px;">'+'</span></button><p style="display:none">'+json[i].diary+'</p><div>'; } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。