JavaScript本地存储实践(html5的localStorage和ie的userData)的实例页面

      var editor = document.getElementById( " editor ");
    editor.value= "";
     var UserData = {
        userData :  null,
        name : location.hostname,
         // this.name = "css88.com";

        init:function(){
             if (!UserData.userData) {
                 try {
                    UserData.userData = document.createElement( ' INPUT ');
                    UserData.userData.type =  " hidden ";
                    UserData.userData.style.display =  " none ";
                    UserData.userData.addBehavior ( " #default#userData ");
                    document.body.appendChild(UserData.userData);
                     var expires =  new Date();
                    expires.setDate(expires.getDate()+ 365);
                    UserData.userData.expires = expires.toUTCString();
                }  catch(e) {
                     return  false;
                }
            }
             return  true;
        },

        setItem : function(key, value) {

             if(UserData.init()){
                UserData.userData.load(UserData.name);
                UserData.userData.setAttribute(key, value);
                UserData.userData.save(UserData.name);
            }
        },

        getItem : function(key) {
             if(UserData.init()){
            UserData.userData.load(UserData.name);
             return UserData.userData.getAttribute(key)
            }
        },

        remove : function(key) {
             if(UserData.init()){
            UserData.userData.load(UserData.name);
            UserData.userData.removeAttribute(key);
            UserData.userData.save(UserData.name);
            }

        }
    };

    window.onbeforeunload=function(){
         if(!window.localStorage){
            UserData.setItem( ' editor-text ',editor.value);
        } else{
            localStorage.setItem( ' editor-text ',editor.value);
        }

    };
    window.onload=function(){
         if(!window.localStorage){
             if(UserData.getItem( ' editor-text ')==undefined) {
                editor.value= "";
            } else{
                editor.value=UserData.getItem( ' editor-text ');
            }
        } else{
             if(localStorage.getItem( ' editor-text ')!= null){
                editor.value=localStorage.getItem( ' editor-text ');
            } else{
                editor.value= "";
            }
        } 

    };
    document.getElementById("save").onclick=function(){
        //localStorage.removeItem('text');
        if(!window.localStorage){
            UserData.remove('editor-text');
        }else{
            localStorage.removeItem('editor-text');
        }
    }

 

 引用自:http://www.css88.com/demo/localstorage/

你可能感兴趣的:(localStorage)