jquery cookie插件的问题

Trouble with the jquery cookie plugin

本文关键字:问题 插件 cookie jquery      更新时间:2023-09-26

我有这个

<button class="create">create</button>
<button class="check">check</button>

$(document).ready(function() {
   $("#set_state").change(function() {
       var theState = $(this).val();
       $.cookie('set_state', theState, {
           expires: 5,
           path: '/'
       });
  });
  $(".check").click(function() {
      alert("Your Selected Value from Cookie is : " + $.cookie('set_state'));
  });
  $(".delete").click(function() {
       $.cookie('set_state', '', {
        expires: -1
       });
       $("#set_state").val("");
       alert('Cookie is deleted now, try to get cookie..!');
   });
});

我从另一个线程得到的。我对此很陌生,我不知道为什么我的警报显示"您从 Cookie 中选择的值是:未定义"。我错过了什么?

设置任何值之前,您首先需要创建cookie。

$(document).ready(function() {
    var $set_state = $.cookie('set_state');
    ... etc

然后,您可以使用 var 名称来引用 cookie

alert("Your Selected Value from Cookie is : " + $set_state );

请注意,Cookie 的值将在同一会话中保持null,直到下一页刷新。

参见 JSFIDDLE

单击创建检查,它将返回null。然后刷新页面并检查将返回 cookie 的值。