cookie设置、获取、移除函数的封装

<!DOCTYPE html>
<!--
作者:1243860037@qq.com
时间:2017-10-26
描述:
通过key值获取具体的值
若显示页面加载出错,点击右上角-》选项-》隐私-》删除cookie在试
-->
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<style>

</style>
<script>
window.onload=function()
{
/*var odate=new Date();
odate.setDate(odate.getDate()+5); //当前时间5天后
document.cookie='username=xiaoxiaoyao;expires='+odate.toGMTString();
document.cookie='hobby=打篮球;expires='+odate.toGMTString();*/
//上面的是设置cookie的,我们也能将设置cookie封装
//设置cookie函数
function setCookie(key,value,t)
{
var odate=new Date();
odate.setDate(odate.getDate()+t);
document.cookie=key+'='+value+';expires='+odate.toGMTString();
}
//获取cookie函数
function getCookieByKey(key) //因为得到的cookie会是所有的cookie并且以 分号加空格串联
{ //本函数的作用就是用split一次一次的分割,将其分成我们需要的
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]); //decodeURI是解码,
}

}
}
//移除cookie函数
function removeCookie(key)
{
setCookie(key,'',-1)//-1:昨天,所以过期
}
setCookie('username','liuliu',10);
setCookie('hobby','打游戏',12);
removeCookie('hobby')
alert(getCookieByKey('username'));
alert(getCookieByKey('hobby'));

}
</script>
</head>
<body>


</body>
</html>

posted on 2017-10-26 21:36  xiaoxiaoyao61  阅读(448)  评论(0编辑  收藏  举报

导航