AutoSave/自动存储功能实现

  转自: 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