如何在 JavaScript 中创建 Cookie?


使用 Cookie 是记住和跟踪偏好、购买情况、佣金和其他信息的最有效方法,而这些信息对于改善访问者体验或网站统计至关重要。

创建 Cookie 的最简单方法是将字符串值分配给 document.cookie 对象,如下所示。

document.cookie = "key1=value1;key2=value2;expires=date";

其中,expires 属性是可选的。如果你在此属性中提供有效的日期或时间,那么 Cookie 将在给定的日期或时间过期,此后便无法访问 Cookie 值。

注意 - Cookie 值可能不包含分号、逗号或空格。因此,你可能需要使用 JavaScript escape() 函数对值进行编码,然后再将其存储在 Cookie 中。如果你这样做,当你读取 Cookie 值时,你还必须使用相应的 unescape() 函数。

示例

你可以尝试以下代码。它在输入 Cookie 中设置了客户名称。

现场演示

<html>
   <head>
      <script>
         <!--
            function WriteCookie() {
               if( document.myform.customer.value == "" ) {
                  alert("Enter some value!");
                  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>

更新于:2020 年 6 月 16 日

690 人次观看

职业生涯起点

完成本课程以获取认证

开始
广告
© . All rights reserved.