2012-10-24 40 views
1

我正在使用jquery cookies插件,以便在用戶每次訪問頁面時增加cookie的值。我這樣做是爲了能夠在第一次訪問時顯示一些內容,然後在第二次訪問時顯示出不同的內容,然後再進行一些操作。jquery cookie增加每次訪問?

因此,我需要確定用戶的第一次訪問,他們的第二次訪問和所有訪問後。

var cookieTime = jQuery.cookie('shownDialog'); 
cookie_value = parseInt(cookieTime); 

if (cookieTime != 'true') {   
    jQuery.cookie('shownDialog', '1', 'true', {expires: 7}); 
    cookie_value ++; 
} 

else if (cookieTime == 'true' && cookie_value > 0){ 
    cookie_value ++; 
} 

我一直在使用的這段代碼在每次刷新頁面時都會重置。而不是在cookie中保存值。我不確定保存cookie的價值並在頁面被刷新時每次增加cookie的最佳方式?

+1

問題是,您在增加cookie後沒有保存cookie。 –

回答

2

我不認爲

jQuery.cookie('shownDialog', '1', 'true', {expires: 7}); 

是有效形式。它應該是

jQuery.cookie(cookiename, cookieval, extra); 

來源:https://github.com/carhartl/jquery-cookie

如果你想檢查Cookie設置,檢查它是否爲空。

// Check if the cookie exists. 
if (jQuery.cookie('shownDialog') == null) { 
    // If the cookie doesn't exist, save the cookie with the value of 1 
    jQuery.cookie('shownDialog', '1', {expires: 7}); 
} else { 
    // If the cookie exists, take the value 
    var cookie_value = jQuery.cookie('shownDialog'); 
    // Convert the value to an int to make sure 
    cookie_value = parseInt(cookie_value); 
    // Add 1 to the cookie_value 
    cookie_value++; 

    // Or make a pretty one liner 
    // cookie_value = parseInt(jQuery.cookie('shownDialog')) + 1; 

    // Save the incremented value to the cookie 
    jQuery.cookie('shownDialog', cookie_value, {expires: 7}); 
}