<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript的Cookie操作</title>
<script>
function setCookie(key,value,exdays) {
var d = new Date();
/*注意点1:这里是以毫秒为单位*/
d.setTime(d.getTime() + exdays * 24 * 60 * 60 *1000);
var expires = "expires = " + d.toUTCString();
/*注意点2:设置后,并没有影响其他键值对,是添加的效果。~*/
document.cookie = key + "=" + value + ";" + expires;
}
function deleteCookie(key) {
setCookie(key,"",-1);
}
function getCookie(key) {
var skey = key + "=";
var arrKeyValue = document.cookie.split(';');
for (var i = 0; i < arrKeyValue.length; i ++){
var c = arrKeyValue[i].trim();
if (c.indexOf(skey) == 0) return c.substring(key.length + 1, c.length);
}
return "";
}
function checkCookie(key) {
var c = getCookie(key);
if (c != null && c != ''){
alert("Cookie已经存在:" + key + "=" + c);
}
else{
c = window.prompt("请输入" + key + "的值","");
if (c != null && c != ''){
setCookie(key,c,1);
}
}
}
function showCookie() {
alert("当前Cookie为:" + document.cookie);
}
</script>
</head>
<body>
<p><small>显示当前的Cookie</small></p>
<button οnclick="showCookie()">点我显示</button>
<hr>
<p><small>设置Cookie的内容为:userName = Liyanq </small></p>
<button οnclick="setCookie('userName','Liyanq',1)">点我设置</button>
<hr>
<p><small>删除Key为userName的Cookie</small></p>
<button οnclick="deleteCookie('userName')">点我删除</button>
<hr>
<p><small>获取Key为userName的Cookie</small></p>
<button οnclick="alert(getCookie('userName'))">点我获取</button>
<hr>
<p><small>监测Key为userNmae的Cookie</small></p>
<button οnclick="checkCookie('userName')">点我监测</button>
</body>
</html>
[php学习十五]javaScript的基本练习5-Cookie
最新推荐文章于 2016-11-17 22:58:08 发布