标签:
1 <html> 2 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 3 <head> 4 <title>js_cookie操作</title> 5 <script language="JavaScript" type="text/javascript"> 6 7 function addCookie(objName, objValue, objHours){//添加cookie 8 var str = objName + "=" + escape(objValue); 9 if (objHours > 0) {//为0时不设定过期时间,浏览器关闭时cookie自动消失 10 var date = new Date(); 11 var ms = objHours * 3600 * 1000; 12 date.setTime(date.getTime() + ms); 13 str += "; expires=" + date.toGMTString(); 14 } 15 document.cookie = str; 16 alert("添加cookie成功"); 17 } 18 19 function getCookie(objName){//获取指定名称的cookie的值 20 var arrStr = document.cookie.split("; "); 21 for (var i = 0; i < arrStr.length; i++) { 22 var temp = arrStr[i].split("="); 23 if (temp[0] == objName) 24 return unescape(temp[1]); 25 } 26 } 27 28 function delCookie(name){//为了删除指定名称的cookie,可以将其过期时间设定为一个过去的时间 29 var date = new Date(); 30 date.setTime(date.getTime() - 10000); 31 document.cookie = name + "=a; expires=" + date.toGMTString(); 32 } 33 34 function allCookie(){//读取所有保存的cookie字符串 35 var str = document.cookie; 36 if (str == "") { 37 str = "没有保存任何cookie"; 38 } 39 alert(str); 40 } 41 42 function $(m, n){ 43 return document.forms[m].elements[n].value; 44 } 45 46 function add_(){ 47 var cookie_name = $("myform", "cookie_name"); 48 var cookie_value = $("myform", "cookie_value"); 49 var cookie_expireHours = $("myform", "cookie_expiresHours"); 50 addCookie(cookie_name, cookie_value, cookie_expireHours); 51 } 52 53 function get_(){ 54 var cookie_name = $("myform", "cookie_name"); 55 var cookie_value = getCookie(cookie_name); 56 alert(cookie_value); 57 } 58 59 function del_(){ 60 var cookie_name = $("myform", "cookie_name"); 61 delCookie(cookie_name); 62 alert("删除成功"); 63 } 64 </script> 65 </head> 66 <body> 67 <form name="myform"> 68 <div> 69 <label for="cookie_name"> 70 名称 71 </label> 72 <input type="text" name="cookie_name" /> 73 </div> 74 <div> 75 <label for="cookie_value"> 76 值 77 </lable> 78 <input type="text" name="cookie_value" /> 79 </div> 80 <div> 81 <label for="cookie_expireHours"> 82 多少个小时过期 83 </lable> 84 <input type="text" name="cookie_expiresHours" /> 85 </div> 86 <div> 87 <input type="button" value="添加该cookie" onclick="add_()"/><input type="button" value="读取所有cookie" onclick="allCookie()"/><input type="button" value="读取该名称cookie" onclick="get_()"/><input type="button" value="删除该名称cookie" onclick="del_()"/> 88 </div> 89 </form> 90 </body> 91 </html>
标签:
原文地址:http://www.cnblogs.com/X-Jonney/p/5457375.html