JavaScript Cookie的使用实例

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Cookie的使用实例</title>
<script>
window.onload = function(){
    var oInp = document.getElementsByTagName('input');
    
    if(getCookie('username')){
        oInp[0].value = getCookie('username');
        }
    
    oInp[1].onclick = function(){   
        setCookie('username',oInp[0].value,10);
        alert('成功');
        }
    oInp[2].onclick = function(){
        removeCookie('username');
        oInp[0].value = '';
        }
    }
    //封装函数增加cookie
    function setCookie(key,value,t){ //名称,值,时间(天)
        var oDate = new Date();
        oDate.setDate(oDate.getDate() + t);
        document.cookie = key + '=' + encodeURI(value) + ';expires=' + oDate.toGMTString();
        }
        
    setCookie('name','123',1);  //名称,值,时间(天)
    
    //封装函数查询cookie的值
    function getCookie(key){
        var arr1 = document.cookie.split('; ');    //分割成数组
        for(var i=0; i<arr1.length; i++){
            var arr2 = arr1[i].split('=');     //再次分割
            if(arr2[0]==key){                  
                return decodeURI(arr2[1]);
                }
            }
        }
    
    //删除cookie
    function removeCookie(key){ //转入键值
        setCookie(key,'',-1);
        }
</script>
</head>
<body>
<input type="text" />
<input type="button" value="登陆" name="username"/>
<input type="button" value="删除" />
</body>
</html> 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值