save class state of multiple divs in cookie

让人想犯罪 __ 提交于 2019-12-25 18:42:45

问题


I have this toggleClass function:

$(document).ready(function() {  
    $("button#playersize").click(function(){
        $("#wrapper").toggleClass("small large");
        $(".divone").toggleClass("small large");
        $(".divtwo").toggleClass("small large");
    });
});

This changes the classes of the divs between "small" and "large" onclick button.

I would like to save the class of the divs (#wrapper, .divone, .divtwo) to a cookie. And on reload, the class should be the saved one.

How do I manage this?

I have the jquery cookie plugin embedded already. My code is probably a bit redundant, sorry.


回答1:


Here is what you can try:

$(document).ready(function() {
    // replace the classes from the cookies
    // example if you want to check the cookie first
    if ($.cookie('class_wrapper').length > 0) {
        $("#wrapper").attr('class', $.cookie('class_wrapper'));
    } else {
        $("#wrapper").attr('class', 'small');
    }
    $(".divone").attr('class', $.cookie('class_divone'));
    $(".divtwo").attr('class', $.cookie('class_divtwo'));
    // bind the click event 
    $("button#playersize").click(function(){
        $("#wrapper").toggleClass("small large");
        $(".divone").toggleClass("small large");
        $(".divtwo").toggleClass("small large");
        // replace the cookie values
        $.cookie('class_wrapper', $("#wrapper").attr('class'));
        $.cookie('class_divone', $(".divone").attr('class'));
        $.cookie('class_divtwo', $(".divtwo").attr('class'));  
    });
});

Caveat: not tested yet



来源:https://stackoverflow.com/questions/8150555/save-class-state-of-multiple-divs-in-cookie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!