Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

jquery - save class state of multiple divs in cookie

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...