使用JavaScript获取和设置单个Cookie值的“最佳”方法是什么

我想每次引用页面时都增加一个cookie值,即使该页面是从缓存中加载的。实现此目的的“最佳”或最简洁的方法是什么?



30秒到达战场
浏览 582回答 3
3回答

莫回无

我见过的大多数旧的Cookie处理功能都使用简单的字符串操作来存储检索值,例如本例,您可以使用其他库,例如cookie-js,这是一个小的(<100行)实用程序,用于cookie访问。我个人在项目中使用jQuery,并且使用jQuery Cookie Plugin,使用起来非常简单:var cookieName = "increment";if ($.cookie(cookieName) == null){&nbsp; $.cookie(cookieName, 1, { expires: 10 });}else{&nbsp; var newValue = Number($.cookie(cookieName)) + 1;&nbsp; $.cookie(cookieName, newValue, { expires: 10 });}

子衿沉夜

最好的方法总是最简单的:function getCookie(name) {&nbsp; return (name = (document.cookie + ';').match(new RegExp(name + '=.*;'))) && name[0].split(/=|;/)[1];}// the default lifetime is 365 daysfunction setCookie(name, value, days) {&nbsp; var e = new Date;&nbsp; e.setDate(e.getDate() + (days || 365));&nbsp; document.cookie = name + "=" + value + ';expires=' + e.toUTCString() + ';path=/;domain=.' + document.domain;}这些函数期望该值是一个简单的字符串,但是如果您愿意或者可以做其他事情的话,您可以始终对其进行JSON.stringify ...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript