<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Cookie的使用实例</title>
<script>
window.onload = function(){
var oInp = document.getElementsByTagName('input');
if(getCookie('username')){
oInp[0].value = getCookie('username');
}
oInp[1].onclick = function(){
setCookie('username',oInp[0].value,10);
alert('成功');
}
oInp[2].onclick = function(){
removeCookie('username');
oInp[0].value = '';
}
}
//封装函数增加cookie
function setCookie(key,value,t){ //名称,值,时间(天)
var oDate = new Date();
oDate.setDate(oDate.getDate() + t);
document.cookie = key + '=' + encodeURI(value) + ';expires=' + oDate.toGMTString();
}
setCookie('name','123',1); //名称,值,时间(天)
//封装函数查询cookie的值
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]);
}
}
}
//删除cookie
function removeCookie(key){ //转入键值
setCookie(key,'',-1);
}
</script>
</head>
<body>
<input type="text" />
<input type="button" value="登陆" name="username"/>
<input type="button" value="删除" />
</body>
</html>
JavaScript Cookie的使用实例
最新推荐文章于 2021-05-20 01:28:06 发布