刷新页面后保留计数器

Keeping a counter after page is refreshed?

本文关键字:保留 计数器 刷新      更新时间:2023-09-26

我需要为我正在制作的游戏保留一个计数器。每次他们赢了一场比赛,我都想在柜台上加一个。然而,每次他们获胜,页面都会刷新以开始新的游戏。即使页面被重新加载,是否有办法保持此计数器的更新?

您可以使用cookie,这里有一个非常简单的jQuery cookie插件示例:

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

用法示例:http://www.electrictoolbox.com/jquery-cookies/

设置cookie:

$.cookie("example", "foo", { expires: 7 });

获取cookie值:

alert( $.cookie("example") );

非常干净和紧凑:)

如果使用兼容的浏览器,则将值存储在cookie或localStorage中。

将其放入cookie中。嗯。。。饼干。好吃的

https://developer.mozilla.org/en/DOM/document.cookie

w3school cookie对此给出了简单的解释。
很快,这是一种将浏览器数据保存在本地机器上的方法。

// So, you may try
setCookie("win_count",value,exdays); // to set some data to "win_count"
// and after the page was reloaded to restore the win counter with the help of:
getCookie("win_count");

使用cookie

jQuery:

$.cookie("example", "foo", { expires: 7 });

纯JavaScript:

function getCookie(name) {
    var matches = document.cookie.match(new RegExp("(?:^|; )" + name.replace(/(['.$?*|{}'(')'[']'''/'+^])/g, '''$1') + "=([^;]*)"))
    return matches ? decodeURIComponent(matches[1]) : undefined
}
function setCookie(name, value, props) {
    props = props || {}
    var exp = props.expires
    if (typeof exp == "number" && exp) {
        var d = new Date()
        d.setTime(d.getTime() + exp * 1000)
        exp = props.expires = d
    }
    if (exp && exp.toUTCString) {
        props.expires = exp.toUTCString()
    }
    value = encodeURIComponent(value)
    var updatedCookie = name + "=" + value
    for (var propName in props) {
        updatedCookie += "; " + propName
        var propValue = props[propName]
        if (propValue !== true) {
            updatedCookie += "=" + propValue
        }
    }
    document.cookie = updatedCookie
}
function deleteCookie(name) {
    setCookie(name, null, {
        expires: -1
    })
}