用cookie实现localstorage功能
生活随笔
收集整理的這篇文章主要介紹了
用cookie实现localstorage功能
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在項目中需要利用到html5的localstorage。但在利用這個屬性的時候卻發現無法達到預定目標。經過不斷的檢查及排除,最后發現原因所在:
項目中使用的瀏覽器是支持localstorage的,但是卻無法使用,具體原因未知(推測可能需要對瀏覽器的環境變量進行相關配置才能直接使用,但我對此無能為力)。
最后,通過上網查詢,發現可以使用cookie實現localstorage的功能(當然數據保存是有期限的),代碼如下:
<script type="text/javascript">//創建localStorage1 var localStorage1Class = function(){this.options = {expires : 60*24*3600,} } localStorage1Class.prototype = {//初實化。添加過期時間 init:function(){var date = new Date();date.setTime(date.getTime() + 60*24*3600);this.setItem('expires',date.toGMTString());},//內部函數參數說明(key) 檢查key是否存在 findItem:function(key){var bool = document.cookie.indexOf(key);if( bool < 0 ){return true;}else{return false;}},//得到元素值 獲取元素值 若不存在則返回 null getItem:function(key){ var i = this.findItem(key);if(!i){var array = document.cookie.split(';') for(var j=0;j<array.length;j++){var arraySplit = array[j];if(arraySplit.indexOf(key) > -1){var getValue = array[j].split('=');//將 getValue[0] trim刪除兩端空格getValue[0] = getValue[0].replace(/^\s\s*/, '').replace(/\s\s*$/, '')if(getValue[0]==key){return getValue[1];}else{return 'null';}}}}},//重新設置元素 setItem:function(key,value){var i = this.findItem(key)document.cookie=key+'='+value;},//清除所有cookie 參數 remove:function(){var array = document.cookie.split(';') for(var cl =0 ;cl<array.length;cl++){var date = new Date();date.setTime(date.getTime() - 100);document.cookie =array[cl] +"=a; expires=" + date.toGMTString();}} } var localStorage1 = new localStorage1Class();localStorage1.init(); </script>轉載:http://blog.csdn.net/xiaosong521/article/details/7733424
轉載于:https://www.cnblogs.com/wawahaha/p/4937964.html
總結
以上是生活随笔為你收集整理的用cookie实现localstorage功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Parallel Programming
- 下一篇: 随机分配座位,共50个学生,使学号相邻的