MAO-EYE 2009-09-22 08:09 采纳率: 100%
浏览 340
已采纳

如何使用 jQuery 设置 / 取消设置 cookie?

How do I set and unset a cookie using jQuery, for example create a cookie named test and set the value to 1?

转载于:https://stackoverflow.com/questions/1458724/how-do-i-set-unset-a-cookie-with-jquery

  • 写回答

12条回答 默认 最新

  • csdnceshi62 2009-09-22 08:11
    关注

    See the plugin:

    https://github.com/carhartl/jquery-cookie

    You can then do:

    $.cookie("test", 1);
    

    To delete:

    $.removeCookie("test");
    

    Additionally, to set a timeout of a certain number of days (10 here) on the cookie:

    $.cookie("test", 1, { expires : 10 });
    

    If the expires option is omitted, then the cookie becomes a session cookie and is deleted when the browser exits.

    To cover all the options:

    $.cookie("test", 1, {
       expires : 10,           // Expires in 10 days
    
       path    : '/',          // The value of the path attribute of the cookie
                               // (Default: path of page that created the cookie).
    
       domain  : 'jquery.com', // The value of the domain attribute of the cookie
                               // (Default: domain of page that created the cookie).
    
       secure  : true          // If set to true the secure attribute of the cookie
                               // will be set and the cookie transmission will
                               // require a secure protocol (defaults to false).
    });
    

    To read back the value of the cookie:

    var cookieValue = $.cookie("test");
    

    You may wish to specify the path parameter if the cookie was created on a different path to the current one:

    var cookieValue = $.cookie("test", { path: '/foo' });
    

    UPDATE (April 2015):

    As stated in the comments below, the team that worked on the original plugin has removed the jQuery dependency in a new project (https://github.com/js-cookie/js-cookie) which has the same functionality and general syntax as the jQuery version. Apparently the original plugin isn't going anywhere though.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(11条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么