前言:今天写了个小练习,把这几天看的东西巩固一下,在这个程序中用到了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[i].diary+'
'; } } }以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。