這個功能很常見。是為了防止瀏覽器崩潰或提交不成功而導致自己辛辛苦苦寫就的東西消失掉。Gmail 裡也這個東西。
現在提供一個js,js是網上下載的,它的原理是將該文字框的東西儲存進一個 Cookie. 如果沒提交成功(原因可能是瀏覽器崩潰),下次訪問該頁面時詢問是否匯入上次儲存的東西。
function AutoSave(it) {var _value = it.value;if (!_value) {var _LastContent = GetCookie('AutoSaveContent');if (!_LastContent) return;if (confirm("Load Last AutoSave Content?")) {it.value = _LastContent;return true;}} else {var expDays = 30;var exp = new Date();exp.setTime( exp.getTime() + (expDays * 86400000) ); // 24*60*60*1000 = 86400000var expires='; expires=' + exp.toGMTString();// SetCookiedocument.cookie = "AutoSaveContent=" + escape (_value) + expires;}}function getCookieVal (offset) {var endstr=document.cookie.indexOf (";",offset);if (endstr==-1) endstr=document.cookie.length;return unescape(document.cookie.substring(offset, endstr));} function GetCookie (name){var arg=name+"=";var alen=arg.length;var clen=document.cookie.length;var i = 0;while (i<clen){var j=i+alen;if (document.cookie.substring(i,j)==arg) return getCookieVal (j);i = document.cookie.indexOf(" ",i)+1;if (i==0) break;}return null;}function DeleteCookie (name) {var exp=new Date();exp.setTime (exp.getTime()-1);var cval=GetCookie (name);document.cookie=name+"="+cval+";expires="+exp.toGMTString();}
在html中添加事件:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Js自動儲存</title> <script src="AutoSave.js" type="text/javascript"></script> </head> <body> <form action="#" method="POST" id="form1" onSubmit="DeleteCookie('AutoSaveContent')"> <table style="width: 100%;"> <tr> <td class="style1"> 文章名 </td> <td><input id="Name" type="text" name="Name" /></td> </tr> <tr> <td class="style1"> 文章內容 </td> <td><textarea id="Content" name="Content" onkeyup="AutoSave(this);" onselect="AutoSave(this);" onclick="AutoSave(this);" ></textarea></td> </tr> <tr> <td colspan="2" style="text-align: center"><input name="提交" type="submit" id="Button1" value="button" /></td> </tr> <tr> <td colspan="2" style="text-align: center"><div id="AutoSaveMsg"> </div></td> </tr> </table> </form></body></html>
1、匯入 js
2、form的 onSubmit 指如果提交了就刪除該 cookie, 而 DeleteCookie 也是自訂的一個函數。
3、textarea 裡的 onkeyup 是指當按鍵時訪問 AutoSave, 用以儲存新寫入的文字。而 onselect 和 onclick 用以新訪問時確定匯入自動儲存的文字。
效果圖如下 :(將下圖另存新檔,然後把副檔名改為rar,就可以得到js源碼)