日期:2014-05-16 浏览次数:20536 次
?
这个是《Html5与css3权威指南》中的一个例子,写出来备用。
?
<!DOCTYPE html> <meta charset="UTF-8"> <title>使用本地数据库实现Web留言本</title> <script> var datatable = null; var db = openDatabase("MyData","1.0","My Database",2*1024*1024); function init() { datatable = document.getElementById("datatable"); showAllData(); } function removeAllData(){ for(var i = datatable.childNodes.length-1;i>=0;i--){ datatable.removeChild(datatable.childNodes[i]); } var tr = document.createElement('tr'); var th1 = document.createElement('th'); var th2 = document.createElement('th'); var th3 = document.createElement('th'); th1.innerHTML = "姓名"; th2.innerHTML = "留言"; th3.innerHTML = "时间"; tr.appendChild(th1); tr.appendChild(th2); tr.appendChild(th3); datatable.appendChild(tr); } function showAllData() { db.transaction(function(tx){ tx.executeSql('create table if not exists MsgData(name TEXT,message TEXT,time INTEGER)',[]); tx.executeSql('select * from MsgData',[],function(tx,rs){ removeAllData(); for(var i=0;i<rs.rows.length;i++){ showData(rs.rows.item(i)); } }); }); } function showData(row){ var tr=document.createElement('tr'); var td1 = document.createElement('td'); td1.innerHTML = row.name; var td2 = document.createElement('td'); td2.innerHTML = row.message; var td3 = document.createElement('td'); var t = new Date(); t.setTime(row.time); td3.innerHTML = t.toLocaleDateString() + " " + t.toLocaleTimeString(); tr.appendChild(td1); tr.appendChild(td2); tr.appendChild(td3); datatable.appendChild(tr); } function addData(name,message,time) { db.transaction(function(tx){ tx.executeSql('insert into MsgData values(?,?,?)',[name,message,time],function(tx,rs){ alert("保存成功。"); },function(tx,error){ alert(error.source+"::"+error.message); }); }); } // End of addData function saveData() { var name = document.getElementById('name').value; var memo = document.getElementById('memo').value; var time = new Date().getTime(); addData(name,memo,time); showAllData(); } // End of saveData </script> <body onload="init()"> <h1>使用本地数据库实现Web留言本</h1> <table> <tr> <td>姓名</td> <td><input type="text" name="name" id="name" /></td> </tr> <tr> <td>留言</td> <td><input type="text" name="memo" id="memo" /></td> </tr> <tr> <td></td> <td> <input type="button" value="保存" onclick="saveData()" /> </td> </tr> </table> <ht> <table id="datatable" border="1"></table> <p id="msg"></p> </body>?
?