最简朴的设置cookie的要领
document.cookie="password=123456";
用expires设置cookie逾期时候
<script>
window.onload=function(){
var oDate=new Date();
oDate.setDate(oDate.getDate()+14);
document.cookie="username=yanyan;expires="+oDate;//用expires设置cookie的逾期时候
// document.cookie="password=123456";
console.log(document.cookie);
}
</script>
封装设置cookie、猎取cookie和删除cookie要领
<!DOCTYPE html>
<html>
<head>
<title>cookie封装</title>
<script>
function setCookie(name,value,iDay){//name名字value值iDay若干天逾期
var oDate=new Date();
oDate.setDate(oDate.getDate()+iDay);//参数传若干天,就逾期若干天
document.cookie=name+"="+value+";expires="+oDate;
}
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 "";//假如没找到返回空字符串。
}
function removeCookie(name){
setCookie(name,1,-1);//设置-1天逾期,代表昨天已逾期
}
window.onload=function(){
setCookie("userName","yanyan",10);//cookie存一个userName=yanyan,10天以后逾期
setCookie("password","123456",14);//14天以后逾期
console.log(document.cookie);//记得用火狐测试
console.log(getCookie("userName"));
}
</script>
</head>
<body>
</body>
</html>
做一个小demo记着用户名
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>event兼容测试</title>
<script>
function setCookie(name,value,iDay){//name名字value值iDay若干天逾期
var oDate=new Date();
oDate.setDate(oDate.getDate()+iDay);//参数传若干天,就逾期若干天
document.cookie=name+"="+value+";expires="+oDate;
}
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 "";//假如没找到返回空字符串。
}
function removeCookie(name){
setCookie(name,1,-1);//设置-1天逾期,代表昨天已逾期
}
window.onload=function(){
var oForm=document.getElementById("form1");
var oUser=document.getElementsByName("user")[0];
oForm.onsubmit=function(){
setCookie("user",oUser.value,14);
}
oUser.value=getCookie("user");
}
</script>
</head>
<body>
<form id="form1" action="http://www.baidu.com">
用户名:
<input type="text" name="user" /><br>
暗码:
<input type="password" name="pass" /><br>
<input type="submit" value="登录" />
</form>
</body>
</html>