AutoSave/自動儲存功能實現

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.