前端设计

   :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

JavaScript中Cookies的用法示例,cookies的用法也是想当广泛的,像网页上的拖动、购物车等等,都是基于Cookie的,希望通过本实例,你能掌握Js中Cookies的具体用法。

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=GB2312" />
<title>Cookies记事贴</title>
<!-- 样式表 -->
<style>
*
{ font-size:12px; font-family:宋体, Arial; font-weight:normal; color:#333; } /*规定了所有的字体样式*/
textarea
{ width:100%; height:98%; border:1px solid black; } /*定义多行文本框的样式*/
</style>
<!-- 脚本部分 -->
<script>

function read_cookie(key){
var str, ary;
str
= document.cookie;
ary
= str.replace(/ *; */g, ";").split(";");
key = escape(key) + "=";
for(var i=0; i<ary.length; i++){
if(ary[i].indexOf(key)==0){
return(unescape(ary[i].split("=")[1]));
}
}
}

function write_cookie(key, value, cookieDomain, cookiePath, expireTime, targetWindow){
var strAppendix="";
strAppendix
+=cookieDomain?";domain="+cookieDomain:"";
strAppendix
+=cookiePath?";path="+cookiePath:"";
strAppendix
+=expireTime?";expires="+expireTime:"";
targetWindow
=targetWindow?targetWindow:top;
targetWindow.document.cookie
=escape(key) + "=" + escape(value) +strAppendix;
}

function loadData(){
if(read_cookie("txt1"))$("txt1").value = read_cookie("txt1");
}

function saveData(){
var dt = new Date();
dt.setYear(dt.getYear()
+2);
write_cookie(
"txt1",$("txt1").value,false,false,dt.toUTCString());
}

function $(str){ return(document.getElementById(str)); }
</script>
</head>
<body style="overflow:auto;" onload="loadData();" onunload="saveData();">
<input type="text" id="txt1" size="200" value="在这里输入内容,关闭页面再次打开,修改后的内容依然存在" />
</body>
</html>

  

posted on 2011-07-19 14:02  前端设计  阅读(314)  评论(0编辑  收藏  举报