对于Cookie,我们经常用到,在js中
1.如何创建Cookie:
document.cookie="name=value";
2.如何读取Cookie
document.cookie
3.如何修改Cookie
document.cookie="name=value2";
4.设置cookie有效时间
document.cookie = "name=value;expires=date“
Date 值为GMT(格林威治时间)格式的日期型字符串
生成方式var date_1 = newDate();
date_1 .setDate(date_1.getDate()+30);
date_1.toGMTString();
小知识
var date=new Date();
date.setTime(date.getTime()+30*60*1000);
//设置date为当前时间+30分
具体实例如下:注册代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
div{
margin: 0 auto;
width: 300px;
height: 150px;
text-align: center;
}
.box2 input{
cursor: pointer;
}
.box2 a{
margin-left: 70px;
color: black;
font-size: 15px;
text-decoration: none;
}
.box2 a:hover{
color: red;
}
</style>
</head>
<body>
<div>
注册<br /><br /><br />
username: <input type="text" id="txt"><br><br>
userpass: <input type="password" id="pass">
</div>
<div class="box2">
<input type="submit" value="提交" οnclick="aa()" class="input_submit">
<a href="js_cookie_denglu.html" class="login">我要登录</a>
</div>
</body>
<script type="text/javascript">
function aa()
{
var username=document.getElementById("txt").value;
var userpass=document.getElementById("pass").value;
//用于保存用户名和密码的方法
var dates=new Date();
dates.setDate(dates.getDate()+1);
document.cookie="username="+username+",pass="+userpass+";expires="+dates.toGMTString()+"";
var cookie_n=document.cookie;
if(cookie_n!=""&&cookie_n.length>=0)
{
alert("注册成功");
}
}
</script>
</html>
登录界面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> div{ margin: 0 auto; width: 300px; height: 150px; text-align: center; } .box2 input{ cursor: pointer; } .box2 a{ margin-left: 70px; color: black; font-size: 15px; text-decoration: none; } .box2 a:hover{ color: red; } </style> </head> <body> <div> 登录<br /><br /><br /> username: <input type="text" id="txt"><br><br> userpass: <input type="password" id="pass"> </div> <div class="box2"> <input type="submit" value="提交" οnclick="aa()"> <a href="js_cookie_zhuce.html">注册</a> </div> </body> <script type="text/javascript"> function aa(){ var username=document.getElementById("txt").value; var userpass=document.getElementById("pass").value; var cookie_n=document.cookie; var un=cookie_n.split(";")[0].split(",")[0].split("=")[1]; var up=cookie_n.split(";")[0].split(",")[1].split("=")[1]; if(username==un&&userpass==up) { alert("登录成功"); } else { alert("账号或密码错误"); } } </script> </html>