本文实例讲述了js使用cookie实现记住用户名功能。分享给大家供大家参考,具体如下:<!DO
本文实例讲述了js使用cookie实现记住用户名功能。分享给大家供大家参考,具体如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>www.jb51.net cookie记住用户名</title>
<meta name="description" content="">
<meta name="keywords" content="">
</head>
<body>
<script>
//1、cookie的使用:document.cookie = 'key=value';可以同时设置多个
// document.cookie="username=longzhoufeng"
// document.cookie="age=03"
//2、cookie的过期时间:document.cookie = '名称=值;expires=' + 字符串格式的时间;
// var myDate=new Date()
// myDate.setDate(myDate.getDate()+3)
// document.cookie="mynameis="+encodeURI("longzhoufeng")+ ";expires="+myDate.toGMTString();
// document.cookie="age=30"
// console.log(decodeURI(document.cookie))
// 解码后输出结果如下:
//mynameis=longzhoufeng; age=30
//3、把上面的封装成一个函数,其中有三个参数是在变化的,key值,value值,T时间
function setCookie(key,value,t){
var myDate=new Date()
myDate.setDate(myDate.getDate()+t)
document.cookie=key+"="+value+ ";expires="+myDate.toGMTString();
}
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]);
}
}
}
function removeCookie(key) {
setCookie(key, '', -1);
}
// setCookie("myName","longzhoufeng",1)
// console.log(getCookie("myName"))
// console.log(removeCookie("myName"))
// alert(typeof myDate)
// 必须将时间格式转换成字符形式
// alert(typeof myDate.toGMTString());
//4、内容最好编码存放,encodeURI
//alert( encodeURI('你好') );
//alert( decodeURI('%E4%BD%A0%E5%A5%BD') )
</script>
<script>
window.onload = function() {
var oUsername = document.getElementById('username');
var oLogin = document.getElementById('login');
var oDel = document.getElementById('del');
if ( getCookie('username') ) {
oUsername.value = getCookie('username');
}
oLogin.onclick = function() {
alert('登陆成功');
setCookie('username', oUsername.value, 5);
}
oDel.onclick = function() {
removeCookie('username');
oUsername.value = '';
}
}
</script>
<input type="text" id="username" />
<input type="button" value="登陆" id="login" />
<input type="button" value="删除" id="del" />
</body>
</html>
js
cookie
记住用户名