1先看一个留言板的小例子
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <fieldset> <legend>留言板</legend> <textarea name="text" rows="10" cols="50" style="resize:none;outline:none;" id="text"></textarea> <input type="button" value="留言" id="addNode" /> <input type="button" value="查询" id="queryNode" /> <input type="button" id="clearBotton" value="收起留言列表"/> <span>删除第</span> <input type="text" id="deleTxt" style="width:30px;outline:none"><span>条</span> <input type="button" id="deleNode" value="删除"/> <input type="button" value="初始化" id="clearNode"/> </fildset> <p id="text2"></p> </body> <script type="text/javascript" src="jquery.js"></script> <script> $("input[type=button]").click(function(e){ switch(e.target.id){ case "addNode": var date=new Date(); var val=$("#text").val(); var str1=date.toLocaleDateString() var str2=date.toLocaleTimeString() if(val!=""){ localStorage.setItem(str1+""+str2,val); alert("留言成功"); $("#text2").empty(); queryNode(); }else{ alert("请留言"); } $("#text").val(""); break; case "queryNode": $("#text2").empty(); queryNode(); break; case "clearNode": localStorage.clear(); $("#text2").empty(); $("#text").val(""); queryNode(); break; case "deleNode": console.log(parseInt($("#deleTxt").val())-1) console.log($("#deleTxt").val()) if(localStorage.length>0&&$("#deleTxt").val()<=localStorage.length&&$("#deleTxt").val()>0){ localStorage.removeItem(localStorage.key(parseInt($("#deleTxt").val())-1)); }else{ alert("您没有那么多留言可以清除~~") } $("#text2").empty(); queryNode(); break; case "clearBotton": $("#text2").empty(); break; default: break; } function queryNode(){ for(var i=0;i<localStorage.length;i++){ var key=localStorage.key(i); console.log(key); var value=localStorage.getItem(key); var date = new Date(); //date.setTime(key); //var str = date.toGMTString(); var str1=date.toLocaleDateString() var str2=date.toLocaleTimeString() //key(i)获得相应的键,再用getItem()方法获得对应的值 /*$("#text2").append(‘第‘+(i+1)+"条:"+value+"。"+str1+" "+str2)*/ $("#text2").append(‘第‘+(i+1)+"条:"+value+"。"+key); $("<br/><br/>").appendTo($(‘#text2‘)); } } }) </script>
时间: 2024-11-26 04:18:24