用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个学生,使学号相邻的