二话不说,先上代码:
1 <body> 2 <div><textarea id="trCon" cols="30" rows="10"></textarea></div> 3 <div><input type="button" value="发表" onclick="PostCon()"><input type="button" value="清除" onclick="Clear()"></div> 4 <div id="dCon"></div> 5 </body>
此代码为一个简单留言板:
-------------------------------------------
--------------------------------------------
LocalStorage 简单理解的话,有点像cookie。将发表的评论保存在本地,浏览器刷新的时候会从本地加载评论
js代码:
<script type="text/javascript"> $(function(){ if (localStorage.getItem("k_con")!=null) { ("k_con",$("#dCon").html(localStorage.getItem("k_con"))); } }) function PostCon(){ var sCon = $("#trCon").val(); $("#dCon").append("<div>" +sCon+ "</div>"); localStorage.setItem("k_con",$("#dCon").html()); } function Clear(){ $("#dCon").html(""); localStorage.clear(); } </script>
效果:
------------------------------------------
------------------------------------------
所有代码:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>留言板</title> 6 <script type="text/javascript" src="js/jquery.js"></script> 7 <script type="text/javascript"> 8 $(function(){ 9 if (localStorage.getItem("k_con")!=null) { 10 ("k_con",$("#dCon").html(localStorage.getItem("k_con"))); 11 } 12 }) 13 function PostCon(){ 14 var sCon = $("#trCon").val(); 15 $("#dCon").append("<div>" +sCon+ "</div>"); 16 localStorage.setItem("k_con",$("#dCon").html()); 17 } 18 function Clear(){ 19 $("#dCon").html(""); 20 localStorage.clear(); 21 } 22 </script> 23 </head> 24 <body> 25 <div><textarea id="trCon" cols="30" rows="10"></textarea></div> 26 <div><input type="button" value="发表" onclick="PostCon()"><input type="button" value="清除" onclick="Clear()"></div> 27 <div id="dCon"></div> 28 </body> 29 </html>
时间: 2024-12-25 17:32:59