日期:2014-05-17  浏览次数:20735 次

html5本地存储-留言板
<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="gb2312">
        <title>HTML5每日一练之JS API-本地存储LocalStorage 留言板 | 前端开发网(W3Cfuns.com)!</title>
<script type="text/javascript">
var Storage =
{
        saveData:function()//保存数据
        {
                var data = document.querySelector("#post textarea");
                if(data.value != "")
                {
                        var time = new Date().getTime() + Math.random() * 5;//getTime是Date对象中的方法,作用是返回 1970年01月01日至今的毫秒数
                        localStorage.setItem(time, data.value + "|" + this.getDateTime());//将毫秒数存入Key值中,可以降低Key值重复率
                        data.value = "";
                        this.writeData();
                }
                else
                {
                        alert("请填写您的留言!");
                }
        },
        writeData:function()//输出数据
        {
                var dataHtml = "", data = "";
                for(var i = localStorage.length-1; i >= 0; i--)//效率更高的循环方法
                {
                        data = localStorage.getItem(localStorage.key(i)).split("|");
                        dataHtml += "<p><span class=\"msg\">" + data[0] + "</span><span class=\"datetime\">" + data[1] + "</span></p>";
                }
                document.getElementById("comment").innerHTML = dataHtml;
        },
        clearData:function()//清空数据
        {
                if(localStorage.length > 0)
                {