zoukankan      html  css  js  c++  java
  • userData IE

    蛮讨厌IE的,因为他常常需要特别照顾,就像DOM Storage(sessionStorage和localStorage)只能支持IE8+,对于以下的只能使用userData。

    原理:通过在document元素后面附加一个专属的“DHTML行为”来实现客户端存储,

     var memory=document.createElement("div");//创建一个元素
     memory.style.display="none";//将其隐藏
     memory.style.behavior="url('#default#userData')"; //附加userData行为
     document.body.appendChild(memory);//将其添加到document元素中

    一旦给元素赋予了“userData”行为,该元素就拥有了load()和save()方法,load()方法用于载入存储的数据。使用它的时候必须传递一个字符串作为参数——类似于一个文件名,该参数用来指定要载入的存储数据。当数据载入的时候,就可以通过该元素的属性来访问这些名值对形式的数据。

    可以使用getAttribute()来查询这些数据,通过setAttribute()方法设置属性,然后调用save()方法可以存储性的数据,而要删除数据,通过使用removeAttribute()方法,然后调用save()方法即可。

    IE userData Behavior
    MethodsDescription
    getAttribute(attr) 获取存储对象中属性值
    load(name) 载入存储数据对象
    removeAttribute(attr) 删除存储对象中的属性
    save(name) 更新存储数据对象
    setAttribute(attr, value) 设置存储对象中的键对值
    properties  
    expires 数据的有效期
    XMLDocument Returns a reference to the XML Document of the persisted object.

    基于userData实现部分存储API

    /*基于IE的userData实现,只有在IE中有效,保存名为UserDataStorage.js*/
        function UserDataStorage(maxage){
            //创建一个document元素鼻骨附加userData行为
            //因此该元素得save()和loda()方法
            var memory=document.createElement("div");
            memory.style.display="none";
            memory.style.behavior="url('#default#userData')"; //附加userData行为
            document.body.appendChild(memory);
    
            //如果传递了maxage参数(单位为秒),则将其设置为userData的有效期,以毫秒为单位
            if(maxage){
                var now=new Date().getTime(); //当前时间
                var expires=now+maxage*1000;//当前时间加上有效期就等于过期时间
                memory.expires=new Date(expires).toUTCString(); //设置userData的过期时间
            }
    
            //通过载入存储的数据初始化memory元素
            //参数是任意的,只要是在保存的时候存在的就可以了
            memory.load("UserDataStorage"); //载入存储数据
    
    
            this.getItem=function(key){ //通过属性来获取保存的值
                return memory.getAttribute(key) || null;
            };
            this.setItem=function(key,value){
                memory.setAttribute(key,value); //已设置属性的形式来保存数据
                memory.save("UserDataStorage"); //保存数据改变后的状态
            };
            this.removeItem=function(key){
                memory.removeAttribute(key); //删除存储的数据
                memory.save("UserDataStorage"); //再次保存状态
            }
        }

    因为以上只能针对ie所以要在最后写上

        <!--[if IE]>
        <script src="UserDataStorage.js"></script>
        <![endif]-->

    userData允许存储的数据量比cookie大,但是却比localStorage以及sessionStorage允许存储的数据量要小。

  • 相关阅读:
    131. Palindrome Partitioning
    130. Surrounded Regions
    129. Sum Root to Leaf Numbers
    128. Longest Consecutive Sequence
    125. Valid Palindrome
    124. Binary Tree Maximum Path Sum
    122. Best Time to Buy and Sell Stock II
    121. Best Time to Buy and Sell Stock
    120. Triangle
    119. Pascal's Triangle II
  • 原文地址:https://www.cnblogs.com/RachelChen/p/5435086.html
Copyright © 2011-2022 走看看