HTML5 local storage save .toggleClass

前端 未结 2 1370
孤独总比滥情好
孤独总比滥情好 2020-12-20 08:36

How Can I save the toggled class into HTML 5 local storage?

This is my simple toggle function:

 /* Toggle */
    $(\'.bar-toggle\').on(\'click\',func         


        
2条回答
  •  死守一世寂寞
    2020-12-20 09:38

    U can use method "$(element).hasClass( string class )"

    Example:

    $('.bar-toggle').on('click',function(){
        if ($('.container').hasClass('.with_toggle')) {
           // mark as false 'cos in the next step u remove class .with_toggle
           localStorage.setItem("container_with_toggle", 0);
        } else {
           // mark as true 'cos in the next step u add class .with_toggle
           localStorage.setItem("container_with_toggle", 1);
        }
        $('.container').toggleClass('with_toggle');
    });
    

    When u access to localStorage:

    var container_with_toggle = localStorage.getItem('container_with_toggle'); // return string zero or one ("0" or "1")
    //So, u can use ternary
    container_with_toggle = (container_with_toggle === "1") ? true : false;
    

    And, if you set value like boolean localStorage.setItem("container_with_toggle", true), u can use ternary operator or JSON.parse.

    var container_with_toggle = localStorage.getItem('container_with_toggle'); // return string with boolean notation ("false" or "true")
    //Ternary
    container_with_toggle = (container_with_toggle === "true") ? true : false;
    // Or use JSON.parse
    container_with_toggle = JSON.parse(container_with_toggle ); // return boolean true or false
    

    Remember, in some browser u need use window.localStorage.

    Bye!

提交回复
热议问题