如何记住jQuery Cookie中顾问的正确/错误状态? [英] How to remember true/false state of adviser in cookies in jQuery?

查看:101
本文介绍了如何记住jQuery Cookie中顾问的正确/错误状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下jQuery代码有疑问.此代码是更大的Yii项目的一部分.我希望该顾问在进入站点时可见,然后在关闭以将状态保存到Cookie中时可见.然后,我重新加载页面,它已关闭.如何使用此代码执行此操作?

I have a problem with the following jQuery code. This code is a part of a bigger Yii project. I want this adviser to be visible when I enter site, then when it is closed to save the state in cookies. Then I reload page and it is closed. How can I do this with this code?

var adviserIsVisible = true, 
    adviserCookie = getCookie("adviser"),

    if(adviserCookie != "") {
        adviserIsVisible = adviserCookie;
    }

    if(adviserIsVisible == true){
        $("#adviser-slide-button").html("&lt");                 
        $(".adviser-slide").animate({"left": "0px"});
        adviserIsVisible = false;
    }
    else {
        $("#adviser-slide-button").html("&gt"); 
        $(".adviser-slide").animate({"left": "-206px"});
        adviserIsVisible = true;
    }

    $("#adviser-slide-button").live("click",function(){
        if(adviserIsVisible == true){
            $("#adviser-slide-button").html("&lt");
            $(".adviser-slide").animate({"left": "0px"});
            adviserIsVisible = false;
        }
        else{       
            $("#adviser-slide-button").html("&gt");
            $(".adviser-slide").animate({"left": "-206px"});
            adviserIsVisible = true;
        }

    setCookie("adviser", adviserIsVisible, 1);


    });

推荐答案

设置和检索Cookie的方式是通过我创建的以下两个函数来实现的:

The way I go about setting and retrieving cookies is by the two functions i've created as following:

function SetTheCookie(key, value)
{
    // Expire date for cookie
    var expires = new Date();
    // Set expire date for cookie
    expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
    // Set cookie key and value which is passed in by parameters 
    document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}

function GetTheCookie(key)
{
    // Check to see if there is a cookie matching the value passed in by parameter
    var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
    return keyValue ? keyValue[2] : null;
}

使用SetTheCookieGetTheCookie的示例:

Example of using the SetTheCookie and GetTheCookie:

示例JSFIDDLE

这篇关于如何记住jQuery Cookie中顾问的正确/错误状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆