function getCookie( name ) {
var start = document.cookie.indexOf( name + "=" );
var len = start + name.length + 1;
if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
return null;
}
if ( start == -1 ) return null;
var end = document.cookie.indexOf( ";", len );
if ( end == -1 ) end = document.cookie.length;
return unescape( document.cookie.substring( len, end ) );
}
function setCookie( name, value, expires, path, domain, secure ) {
var today = new Date();
today.setTime( today.getTime() );
if ( expires ) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );
document.cookie = name+"="+escape( value ) +
( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}
function deleteCookie( name, path, domain ) {
if ( getCookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
实例:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test js control cookie</title>
<script type="text/javascript">
function setCookie(name,value)//两个参数,一个是cookie的名子,一个是值
{
var Days = 30; //此 cookie 将被保存 30 天
var exp = new Date(); //new Date("December 31, 9998");
exp.setTime(exp.getTime() + Days*24*60*60*1000);//设置时间
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); //设置cookies
}
function getCookie(name)//取cookies函数
{
var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));//正则表达式
if(arr != null) {
return unescape(arr[2]);
}
return null;
}
function delCookie(name)//删除cookie
{
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval=getCookie(name);
if(cval!=null) {
document.cookie= name + "="+cval+";expires="+exp.toGMTString();//通过制造过期来删除cookie
}
}
//setCookie ("xiaoqi", "3")
//alert(getCookie('xiaoqi'));
//delCookie("xiaoqi");
//alert(getCookie('xiaoqi'));
</script>
</head>
<body>
<input type="button" value="set cookie" οnclick="setCookie('haha', '26');" />
<input type="button" value="get cookie" οnclick="alert(getCookie('haha'));" />
<input type="button" value="delete cookie" οnclick="delCookie('haha');" />
</body>
</html>