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
624 views
in Technique[技术] by (71.8m points)

jquery - Keeping toggled class after page refresh

I think this has been done many times before but despite reading some posts about cookies couldn't get my head round it.

I have a second body class with different fonts for the whole site which is accessed when the client clicks a link to change font. Ideally, instead of this being on a page-by-page basis, the new class would 'stick' after a new page is visited. My change class code via jQuery looks like this:

$(document).ready(function() {
    $("a#switcher").click(function() {
        $("body").toggleClass("alternate_body");
    });
});

Is there a relatively simple way of achieving this? Thanks in advance.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Cookie approach

You can use a jQuery plugin such as jquery-cookie to simplify cookie access. So your code would become something like this to save the class setting:

$(document).ready(function() {
    var body_class = $.cookie('body_class');
    if(body_class) {
        $('body').attr('class', body_class);
    }
    $("a#switcher").click(function() {
        $("body").toggleClass("alternate_body");
        $.cookie('body_class', $('body').attr('class'));
    });
});

URL Parameters

Another option would be to set a URL parameter on all the links the page when they click #switcher to maintain the state without setting a cookie.


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

...