jquery cookie,每次访问cookie的设置值?

时间:2012-12-05 22:25:01

标签: jquery jquery-cookie

我希望显示3个不同的div 第1次访问1 div 第二次访问的第二个div 第3次访问

我认为我有代码可以实现这一点,但它无法正常工作,我无法弄清楚我做错了什么。

$(document).ready(function() { 

    var cookieRCCS = $.cookie('shownDialog');

    console.log(cookieRCCS);

     // Check if the cookie exists.
    if ( cookieRCCS === null ) {
        console.log("1st if statement " + cookieRCCS);
        $("#hellopanel1").show();

        // set the cookie to value 1
        $.cookie('shownDialog', '1', {expires: 7});

    } 
    else if ( cookieRCCS === 1 ) {
        console.log("2nd if statement " + cookieRCCS);      
        $("#hellopanel2").show();

        // If the cookie exists, take the value
        cookie_value = $.cookie('shownDialog');

        // Convert the value to an int to make sure
        cookie_value = parseInt(cookie_value);

        // Add 1 to the cookie_value
        cookie_value++;

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

    }
    else if ( cookieRCCS === 2){
        console.log("3rd if statement " + cookieRCCS);

        $("#hellopanel3").show();

        cookie_value = $.cookie('shownDialog');

        cookie_value = parseInt(cookie_value);

        cookie_value++;

        $.cookie('shownDialog', cookie_value, {expires: 7});
    }

    else{
        console.log("4th Time Here");
    }

});

2 个答案:

答案 0 :(得分:1)

这将通过简单而优雅的case语句解决您的问题,以便以级联方式正确触发代码片段:

$(document).ready(function() { 
    var cookieRCCS = (+$.cookie('shownDialog')) + 1;
    $.cookie('shownDialog', cookieRCCS,{expires: 7});

    console.log(cookieRCCS);

    switch (cookieRCCS) {
        case 1:
            console.log("1st if statement " + cookieRCCS);
            $("#hellopanel1").show();
            break;

        case 2:
            console.log("2nd if statement " + cookieRCCS);      
            $("#hellopanel2").show();
            break;

        case 3:
            console.log("3rd if statement " + cookieRCCS);
            $("#hellopanel3").show();
            break;

        default:
            console.log("4th+ Time Here");
    }
});

答案 1 :(得分:0)

因为您正在向cookie写入字符串,但是使用===检查类型。只需将if比较更改为==或执行var cookieRCCS = +$.cookie('shownDialog');将其转换为数字(这意味着您必须检查cookieRCCS == 0而不是null