创建cookie的最简单方法是为document.cookie对象分配一个字符串值,如下所示:
document.cookie = "key1=value1;key2=value2;expires=date";
这里的“ expires”属性是可选的。如果为该属性提供有效的日期或时间,则cookie将在给定的日期或时间到期,此后,将无法访问cookie的值。
请尝试以下方法。它在输入cookie中设置客户名称。
<html> <head> <script> <!-- function WriteCookie() { if( document.myform.customer.value == "" ) { alert("输入一些值!"); return; } cookievalue= escape(document.myform.customer.value) + ";"; document.cookie="name=" + cookievalue; document.write ("Setting Cookies : " + "name=" + cookievalue ); } //--> </script> </head> <body> <form name="myform" action=""> Enter name: <input type="text" name="customer"/> <input type="button" value="Set Cookie" onclick="WriteCookie();"/> </form> </body> </html>
由于document.cookie对象的值,读取cookie就像编写一个cookie一样简单。因此,只要您想访问cookie,就可以使用此字符串。document.cookie字符串将保留由分号分隔的name = value对的列表,其中name是cookie的名称,value是其字符串值。
您可以尝试运行以下代码来读取Cookie
<html> <head> <script> <!-- function ReadCookie() { var allcookies = document.cookie; document.write ("All Cookies : " + allcookies ); //获取数组中的所有cookie对 cookiearray = allcookies.split(';'); //现在从该数组中取出键值对 for(var i=0; i<cookiearray.length; i++) { name = cookiearray[i].split('=')[0]; value = cookiearray[i].split('=')[1]; document.write ("Key is : " + name + " and Value is : " + value); } } //--> </script> </head> <body> <form name="myform" action=""> <p> click the following button and see the result:</p> <input type="button" value="Get Cookie" onclick="ReadCookie()"/> </form> </body> </html>