进一步阅读: 本地存储:在HTML5 localStorage中存储对象 本地存储浏览器支持: http://caniuse.com/#search=localstorage 使用JSON序列化:在jQuery中序列化为JSON Modernizr文档: http://modernizr.com/docs/ Let's say i have some textboxes/textareas of which the values have to be stored. The values have to be stored on key press, so that no data is lost when the user closes the page too early. Here's my current code (using cookies):function createCookie(name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = '; expires=' + date.toGMTString(); } else var expires = ''; document.cookie = name + '=' + value + expires + '; path=/';}$('input').keyup(function () { var $this = $(this); createCookie($this.attr('name'), $this.val(), 1);});jsFiddleThis works great.With just 4 textboxes i see no problems but imagine having 50+ textboxes or textareas (not accounting usability/user experience). Will this cause any problems?I'm open to any suggestions/alternatives 解决方案 As Jamie suggested local storage is a really good approach, cookies could be used as a fallback if Local Storage is not supported.On the snippet you have provided you have binded the cookie rewrite process in the keyup event, in order to avoid any data loss.I have implemented a more neat solution , when the user unloads the window I have tried to serialise the form data and store it.//save data generic functionfunction saveData() { var dataObj = JSON.stringify($("input,textarea").serializeObject()); if (!Modernizr.localstorage) { saveToLocalStorage(dataObj); } else { createCookie("jsonobj", dataObj, 1); }}Modernizr is used to detect when local storage is available. Furthermore , I have found that using separate cookies for each field is an overkill, I have used a single JSON string instead.Full jsFiddele example: http://jsfiddle.net/ARUM9/5/Further reading:Local storage :Storing Objects in HTML5 localStorageLocal storage browser support: http://caniuse.com/#search=localstorageUsing JSON serialisation : Serializing to JSON in jQueryModernizr documentation: http://modernizr.com/docs/ 这篇关于如何将这些数据存储在cookie中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-31 05:36