2012-08-01 58 views
0

我需要爲我正在製作的遊戲保留一個計數器。每次他們贏得一場比賽,我都想在櫃檯上添加一個。但是,每次他們獲勝時,頁面都會刷新以開始新的遊戲。即使頁面重新加載,是否有辦法保持此計數器更新?在頁面刷新後保持計數器?

+0

儲存於餅乾嗎? – 2012-08-01 16:43:04

+0

存儲在cookie中或使用DOM存儲或存儲到數據庫 – 2012-08-01 16:43:39

回答

0

如果使用兼容的瀏覽器,將值存儲在cookie或localStorage中。

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

使用cookies

的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 
    }) 
}