什么是“最好的"?使用 JavaScript 获取和设置单个 cookie 值的方法 [英] What is the "best" way to get and set a single cookie value using JavaScript

查看:17
本文介绍了什么是“最好的"?使用 JavaScript 获取和设置单个 cookie 值的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在每次引用页面时增加 cookie 值,即使页面是从缓存加载的.实现此目的的最佳"或最简洁的方法是什么?

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?

推荐答案

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

Stolen from 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);
}

使用它:

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

正如评论中所指出的,您应该转换为 int,因为 cookie 以字符串形式存储和返回.使用 foo++++foo 实际上会为你转换,但确切地知道你在使用什么更安全:

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:

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

这篇关于什么是“最好的"?使用 JavaScript 获取和设置单个 cookie 值的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆