标签:def 表示 ip协议 点赞 打开 hat 游戏 doctype name
设置 会话级默认路径: document.cookie = "name=abc" cookie的格式要求,名称=值 在cookie 的名或值 中 不能使用分号(;)、逗号(,)、等号(=)以及空格这是cookie的赋值规则 指定有效期: 设置cookie的保存时间,通过给expires添加一个日期,设置cookie的过期时间 此处可以借用Date(); var date = new Date(); date.setDate(date.getDate()+28); 表示获取当前日期的天数,增加28天之后,重新设置给日期,此时date就表示未来的某个时间 document.cookie = "name=abc;expires=" + date; 此句表示,此条cookie在date的时间时效,而date的时间为当前日期加上28,也就是28天之后cookie失效 指定路径: document.cookie = "user=admin;path=/;expires="+d; 获取 var str = document.cookie; str返回当前cookie的值,以字符串的形式 删除 删除cookie,相当于将cookie的有效时间设置为负。
function setCookie(key,val,options){ //设置 options = options || {}; var time = ""; if(options.expires){ var d = new Date(); d.setDate(d.getDate()+options.expires); time = ";expires="+d; } var path = ""; if(options.path){ path = ";path=" + options.path } document.cookie = key + "=" + val + time + path; } function getCookie(key){ //获取 var arr = document.cookie.split("; "); var v = ""; arr.forEach((val)=>{ if(val.split("=")[0] === key){ v = val.split("=")[1]; }; }) return v; } function removeCookie(key,options){ //删除 options = options || {}; options.expires = -1; setCookie(key,12321,options); }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title></title> <link rel="stylesheet" href="../project/libs/bootstrap.css"> <script src="cookie.js"></script> <style> span {display: none;} </style> </head> <body> <form> <label for="user">用户名为:</label> <input type="text" id="user" name="user" value=""><br> <label for="pass">密码为:</label> <input type="text" id="pass" name="pass" value=""><br> <label for="check">是否记住密码</label> <input type="checkbox" name="check" id="check" value="y"> <input type="button" id="button" value="登录"><br> <span>请不要再公共电脑上勾选此选项</span> </form> </body> <script> document.onselectstart = function(eve){ eve.preventDefault(); } class Login{ constructor(){ this.user = document.getElementById("user"); this.pass = document.getElementById("pass"); this.check = document.getElementById("check"); this.span = document.querySelector("span"); this.btn = document.getElementById("button"); this.events(); this.getCookie(); } events(){ var that = this; this.check.onclick = function(){ that.onoff = this.checked; if(this.checked){ that.span.style.display = "block"; }else{ that.span.style.display = "none"; } } this.btn.onclick = function(){ that.u = that.user.value; that.p = that.pass.value; if(!that.onoff) return; that.setCookie(); } } setCookie(){ var usermsg = { user:this.u, pass:this.p } setCookie("loginmsg",JSON.stringify(usermsg),{ expires:30 }); } getCookie(){ this.loginmsg = getCookie("loginmsg") ? JSON.parse(getCookie("loginmsg")) : { user:"", pass:"" }; this.user.value = this.loginmsg.user; this.pass.value = this.loginmsg.pass; } } new Login(); </script> </html>
标签:def 表示 ip协议 点赞 打开 hat 游戏 doctype name
原文地址:https://www.cnblogs.com/wuziqiang/p/12077596.html