localStorage实现便签小程序
前言:今天写了个小练习,把这几天看的东西巩固一下,在这个程序中用到了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>'; } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)