JavaScript之cookie

cookie

作用

cookie用于浏览器保存信息,一般用于自动登陆、记住用户名。

特性

1、同一个域名中的所有页面共享一套cookie。
2、数量大小有限,4k—10k。
3、具有过期时间

在JS中使用cookie

document.cookie 设置或查看cookie

设置cookie的格式:名字=值
例如:document.cookie = ‘zhangsan = 1234124’;
注意:不同名字的cookie不会覆盖,只有名字相同的cookie会覆盖。

设置过期时间expires
格式:expires = 时间
注意:设置过期时间需要通过Date()对象。

//设置4天后过期
var oDate = new Date();
oDate.setDate(getDate()+4);
document.cookie = 'name = value;expires=' + oDate;

封装cookie的使用

//设置cookie
function setCookie(name,value,iDay){
    var oDate = new Date();
    oDate.setDate(getDate());
	document.cookie = name + '=' + value + ';expires = ' + oDate;
}
//获取cookie
function getCookie(name){
	var arr = document.cookie.split('; ');
	for(var i=0; i<arr.length; i++){
		var arr2 = arr[i].split('=');
		if(arr2[0] == name){
			return arr2[1];
		}
	}
	return '';
}
//删除cookie
function removeCookie(name){
	setCookie(name,1,-1);
}

封装cookie测试实例

记录上次登陆用户名

<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <script type="text/javascript">
      window.onload = function (){
        var oForm = document.getElementById('form')[0];
        var oUser = document.getElementsByName('user')[0];
        oForm.onsubmit = function (){
          setCookie('user',oUser.value,14);
        }
        oUser.value = getCookie('user');
      }
    </script>
  </head>
  <body>
    <form id='form' action="www.baidu.com">
      用户名:<input type="text" name="user">
      密  码:<input type="password" name='pwd'>
      <input type="submit">
    </form>
  </body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值