我有以下代码,并且想要对其进行调整以记住所添加的类,以使其在整个站点中都适用。我遇到了Jquery Cookie:https://github.com/carhartl/jquery-cookie,并希望使用它来记住应用的类。如何保存当前状态?

    $.cookie('elemshow.on');
var elemhide = $('.hide-menu'),
    elemshow = $('.show-menu, .show-menu2');

    elemhide.on('click', function(e){
        e.preventDefault();

        $('header').addClass('out-active');
        $('.header-foot').addClass('out-active');
        $('#content').addClass('full-width-added');
        setTimeout(function() {
            try {
                reconstructRn();
            } catch(err) {
            }
            window.dispatchEvent(new Event('resize'));
            elemshow.addClass('active');
        }, 300);

    });

    elemshow.on('click', function(e){
        e.preventDefault();

        $('header').removeClass('out-active');
        $('.header-foot').removeClass('out-active');
        $('#content').removeClass('full-width-added');
        elemshow.removeClass('active');
        setTimeout(function() {
            try {
                reconstructRevolution();
            } catch(err) {

            }
        }, 10);

    });

最佳答案

我会像这样调整您的代码:

/* define elemhide and elemshow */
var elemhide = $('.hide-menu'),
    elemshow = $('.show-menu, .show-menu2');

/* click functions */
elemhide.on('click', function(e){

    e.preventDefault();

    /* cookie = 1 week */
    var date = new Date();
    date.setTime(date.getTime() + (1000 * 60 * 60 * 24 * 7));
    $.cookie('menu_cookie', '0', { expires: date, path: '/' });

    /* set classes */
    $('header').addClass('out-active');
    $('.header-foot').addClass('out-active');
    $('#content').addClass('full-width-added');
    setTimeout(function() {
        try {
            reconstructRn();
        } catch(err) {
            // do something
        }
        window.dispatchEvent(new Event('resize'));
        elemshow.addClass('active');
    }, 300);

});

elemshow.on('click', function(e){

    e.preventDefault();

    /* cookie = 1 week */
    var date = new Date();
    date.setTime(date.getTime() + (1000 * 60 * 60 * 24 * 7));
    $.cookie('menu_cookie', '1', { expires: date, path: '/' });

    /* set classes */
    $('header').removeClass('out-active');
    $('.header-foot').removeClass('out-active');
    $('#content').removeClass('full-width-added');
    elemshow.removeClass('active');
    setTimeout(function() {
        try {
            reconstructRevolution();
        } catch(err) {
            // do something
        }
    }, 10);

});

/* check for existing cookie */
if (!$.cookie('menu_cookie') || $.cookie('menu_cookie') == 0) {
    $('.hide-menu').trigger('click');
} else if ($.cookie('menu_cookie') == 1) {
    $('.show-menu').trigger('click');
}

这是一个小提琴:http://jsfiddle.net/Niffler/B8XBg/我不知道您的HTML,所以我只使用颜色...

关于javascript - jQuery Cookie记住类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23872764/

10-09 18:41