javascript操作coolie

3019 ワード

<script language=javascript> 

//  coolie   

 

function cookie(name){    

   var cookieArray=document.cookie.split("; "); //     cookie       

   var cookie=new Object();    

   for (var i=0;i<cookieArray.length;i++){    

      var arr=cookieArray[i].split("=");       //          

      if(arr[0]==name)return unescape(arr[1]); //      cookie,          

   } 

   return ""; 

} 

 

function delCookie(name)//  cookie

{

   document.cookie = name+"=;expires="+(new Date(0)).toGMTString();

}

 

function getCookie(objName){//       cookie  

    var arrStr = document.cookie.split("; ");

    for(var i = 0;i < arrStr.length;i ++){

        var temp = arrStr[i].split("=");

        if(temp[0] == objName) return unescape(temp[1]);

   } 

}

 

function addCookie(objName,objValue,objHours){      //  cookie

    var str = objName + "=" + escape(objValue);

    if(objHours > 0){                               //         ,      cookie    

        var date = new Date();

        var ms = objHours*3600*1000;

        date.setTime(date.getTime() + ms);

        str += "; expires=" + date.toGMTString();

   }

   document.cookie = str;

}

 

function setCookie(name,value)//    ,   cookie   ,    

{

    var Days = 30; //  cookie      30  

    var exp = new Date();    //new Date("December 31, 9998");

    exp.setTime(exp.getTime() + Days*24*60*60*1000);

    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();

}

function getCookie(name)// cookies          

{

    var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));

     if(arr != null) return unescape(arr[2]); return null;

 

}

function delCookie(name)//  cookie

{

    var exp = new Date();

    exp.setTime(exp.getTime() - 1);

    var cval=getCookie(name);

    if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();

}

</script>

<span onclick='addCookie("gdcloud","1",1)'>add</span>
<span onclick='setCookie("gdcloud","2")'>set</span>
<span onclick='delCookie("gdcloud")'>del</span>
<span onclick='alert(getCookie("gdcloud"))'>watch</span>