当前位置:Gxlcms > JavaScript > AutoSave/自动存储功能实现_javascript技巧

AutoSave/自动存储功能实现_javascript技巧

时间:2021-07-01 10:21:17 帮助过:35人阅读

转自: 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 中应当如此: