zoukankan      html  css  js  c++  java
  • 用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(/^ss*/, '').replace(/ss*$/, '')
                        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

  • 相关阅读:
    搭建Elasticsearch 5.4分布式集群
    Elasticsearch中Head插件的使用
    Elasticsearch6.0及其head插件安装
    elasticsearch 6.2.3安装ik分词
    linux安装elasticsearch
    [Elasticsearch] 多字段搜索 (三)
    [Elasticsearch] 全文搜索 (一)
    [Elasticsearch] 多字段搜索 (二)
    elasticsearch this is not a http port
    基于visual Studio2013解决C语言竞赛题之0704字符串长度
  • 原文地址:https://www.cnblogs.com/wawahaha/p/4937964.html
Copyright © 2011-2022 走看看