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

时间:2021-01-09 02:47:08

I want to increment a cookie value every time a page is referenced even if the page is loaded from cache. What is the "best" or most concise way to implement this?

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

3 个解决方案

#1


28  

Stolen from http://www.quirksmode.org/js/cookies.html#script

从http://www.quirksmode.org/js/cookies.html#script窃取

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toUTCString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

using it:

var oldCount = parseInt(readCookie('hitCount'), 10) || 0;
createCookie('hitCount', oldCount + 1, 7);

as pointed out in the comments, you should cast to an int since cookies are stored and returned as strings. Using foo++ or ++foo will actually cast for you, but it's safer to know exactly what you're working with:

正如评论中指出的那样,您应该转换为int,因为cookie存储并作为字符串返回。使用foo ++或++ foo实际上会为你投射,但是确切知道你正在使用的是更安全的:

var x = "5";  // x = "5" (string)
x += 1;       // x = "51" (string!)
x += 5;       // x = "515" (string!)
++x;          // x = 516 (number)

#2


7  

Most of the old cookie handling functions I've seen use simple string manipulations for storing an retrieving values, like this example, you can use other libraries, like cookie-js, a small (< 100 lines) utility for cookie access.

我见过的大多数旧的cookie处理函数都使用简单的字符串操作来存储检索值,比如这个例子,你可以使用其他库,比如cookie-js,一个小的(<100行)实用程序来访问cookie。

I personally use jQuery on my projects, and I use the jQuery Cookie Plugin, it's really simple to use:

我个人在我的项目中使用jQuery,并且我使用jQuery Cookie插件,它使用起来非常简单:

var cookieName = "increment";

if ($.cookie(cookieName) == null){
  $.cookie(cookieName, 1, { expires: 10 });
}else{
  var newValue = Number($.cookie(cookieName)) + 1;
  $.cookie(cookieName, newValue, { expires: 10 });
}

#3


0  

the best way is always the simplest:

最好的方法总是最简单的:

function getCookie(name) {
  return (name = (document.cookie + ';').match(new RegExp(name + '=.*;'))) && name[0].split(/=|;/)[1];
}

// the default lifetime is 365 days
function setCookie(name, value, days) {
  var e = new Date;
  e.setDate(e.getDate() + (days || 365));
  document.cookie = name + "=" + value + ';expires=' + e.toUTCString() + ';path=/;domain=.' + document.domain;
}

these functions expect the value to be a simple string, but you can always JSON.stringify it if you want or maybe do something else with it...

这些函数期望值是一个简单的字符串,但是你可以随时JSON.stringify它,如果你想要或可能做其他事情...

#1


28  

Stolen from http://www.quirksmode.org/js/cookies.html#script

从http://www.quirksmode.org/js/cookies.html#script窃取

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toUTCString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

using it:

var oldCount = parseInt(readCookie('hitCount'), 10) || 0;
createCookie('hitCount', oldCount + 1, 7);

as pointed out in the comments, you should cast to an int since cookies are stored and returned as strings. Using foo++ or ++foo will actually cast for you, but it's safer to know exactly what you're working with:

正如评论中指出的那样,您应该转换为int,因为cookie存储并作为字符串返回。使用foo ++或++ foo实际上会为你投射,但是确切知道你正在使用的是更安全的:

var x = "5";  // x = "5" (string)
x += 1;       // x = "51" (string!)
x += 5;       // x = "515" (string!)
++x;          // x = 516 (number)

#2


7  

Most of the old cookie handling functions I've seen use simple string manipulations for storing an retrieving values, like this example, you can use other libraries, like cookie-js, a small (< 100 lines) utility for cookie access.

我见过的大多数旧的cookie处理函数都使用简单的字符串操作来存储检索值,比如这个例子,你可以使用其他库,比如cookie-js,一个小的(<100行)实用程序来访问cookie。

I personally use jQuery on my projects, and I use the jQuery Cookie Plugin, it's really simple to use:

我个人在我的项目中使用jQuery,并且我使用jQuery Cookie插件,它使用起来非常简单:

var cookieName = "increment";

if ($.cookie(cookieName) == null){
  $.cookie(cookieName, 1, { expires: 10 });
}else{
  var newValue = Number($.cookie(cookieName)) + 1;
  $.cookie(cookieName, newValue, { expires: 10 });
}

#3


0  

the best way is always the simplest:

最好的方法总是最简单的:

function getCookie(name) {
  return (name = (document.cookie + ';').match(new RegExp(name + '=.*;'))) && name[0].split(/=|;/)[1];
}

// the default lifetime is 365 days
function setCookie(name, value, days) {
  var e = new Date;
  e.setDate(e.getDate() + (days || 365));
  document.cookie = name + "=" + value + ';expires=' + e.toUTCString() + ';path=/;domain=.' + document.domain;
}

these functions expect the value to be a simple string, but you can always JSON.stringify it if you want or maybe do something else with it...

这些函数期望值是一个简单的字符串,但是你可以随时JSON.stringify它,如果你想要或可能做其他事情...