一个完美的JavaScript操作COOKIE类
来源:自学PHP网
时间:2014-09-19 14:47 作者:
阅读:次
[导读] 文章分享一个非常不错的JavaScript操作COOKIE类,有需要的朋友可参考使用。...
代码如下 |
复制代码 |
代码
/**提供客户端cookie操作类
*
* @param string uniqueN 唯一标识
*
* @author (凹凸曼)lyc
* @email jar-c@163.com
*
*/
var cacheLY = function(uniqueN){
var uniqueN = (typeof(uniqueN) != "string") ? "" : "uniqueN_" + uniqueN + "_";
setCookie = function(name, value){
var Days = 1;
var exp = new Date();
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
document.cookie = name + "=" + escape(this.encode(value)) + ";expires=" + exp.toGMTString();
}
getCookie = function(name){
var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
if (arr != null)
return this.unencode(unescape(arr[2]));
return null;
}
delCookie = function(name){
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var tem = this.getCookie(name);
if (tem != null)
document.cookie = "name=" + tem + ";expires=" + exp.toGMTString();
}
encode = function(str){
var temstr = "";
var i = str.length - 1;
for (i; i >= 0; i--) {
temstr += str.charCodeAt(i);
if (i)
temstr += "a";
}
return temstr;
}
unencode = function(str){
var strarr = "";
var temstr = "";
strarr = str.split("a");
var i = strarr.length - 1;
for (i; i >= 0; i--) {
temstr += String.fromCharCode(eval(strarr[i]));
}
return temstr;
}
return {
setValue: function(text){
setCookie(uniqueN, text);
},
clearCache: function(name){
delCookie(name);
},
loadCache: function(){
var temvalue = getCookie(uniqueN);
return temvalue;
}
}
}
|
测试
代码如下 |
复制代码 |
<title>js控制cookie实现客户端缓存</title>
<script src="cache.class.js" type="text/javascript">
</script>
</head>
<body>
<div id="nihao">
</div>
<script type="text/javascript">
/*
* @param string tem 需要缓存的数据
* @param object cache 缓存对象
* @param string re 得到的缓存数据
*
*/
var tem = '<div id="d"><br><br><br>奥特曼在线</div>';
var cache = new cacheLY("123");
cache.setValue(tem);
var re = cache.loadCache();
document.getElementById("nihao").innerHTML = re;
</script>
|
|