当前位置: 首页 > 图文教程 > 网络编程 > Javascript > AutoSave/自动存储功能实现

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 AutoSave/自动存储功能实现


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 136 ::
收藏到网摘: n/a

转自: http://www.fayland.org/journal/AutoSave.html

这个功能很常见。是为了防止浏览器崩溃或提交不成功而导致自己辛辛苦苦写就的东西消失掉。Gmail 里也这个东西。
它的原理是将该文本框的东西存储进一个 Cookie. 如果没提交成功(原因可能是浏览器崩溃),下次访问该页面时询问是否导入上次存储的东西。
function AutoSave(it) { // it 指调用的文本框
var _value = it.value; // 获得文本框的值
if (!_value) {
var _LastContent = GetCookie('AutoSaveContent'); // 获得 cookie 的值,这里的 GetCookie 是个自定义函数,参见源代码
if (!_LastContent) return; // 如果该 cookie 没有值,说明是新的开始
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 = 86400000
var expires='; expires=' + exp.toGMTString();

// SetCookie 这里就是设置该 cookie
document.cookie = "AutoSaveContent=" + escape (_value) + expires;
}
}

而这 HTML 中应当如此:

<script language=JavaScript src='/javascript/AutoSave.js'></script>
<form action="submit" method="POST" onSubmit="DeleteCookie('AutoSaveContent')">
<textarea rows="5" cols="70" wrap="virtual" onkeyup="AutoSave(this);" onselect="AutoSave(this);" onclick="AutoSave(this);"></textarea>
<input type="submit"></form>
第一句导入 js, 第二句的 onSubmit 指如果提交了就删除该 cookie, 而 DeleteCookie 也是自定义的一个函数。参见源代码
textarea 里的 onkeyup 是指当按键时访问 AutoSave, 用以存储新写入的文字。
而 onselect 和 onclick 用以新访问时确定导入自动保存的文字。

大致就是如此。 Enjoy!

源代码:http://www.fayland.org/javascript/AutoSave.js