刷新页面后保持计数器?

时间:2012-08-01 16:41:00

标签: javascript jquery html storage

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

5 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

你可以使用cookies,这是一个非常简单的jQuery cookie插件示例:

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

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

设置Cookie:

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

获取Cookie值

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

非常干净和紧凑:)

答案 2 :(得分:0)

把它放在一个cookie中。嗯...饼干。美味。

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

答案 3 :(得分:0)

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");

答案 4 :(得分:0)

使用Cookie

jQuery的:

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

Pure 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
    })
}
相关问题