如何使用jquery在cookie中保存类名?

时间:2014-11-20 07:51:14

标签: jquery cookies

我不想在页面加载后更改当前的选择类。那么,如何在cookie中保存类名? 的 HTML

<a href="javascript:" class="red-btn">red</a>
<a href="javascript:" class="green-btn">green</a>
<!-- Result -->
<div class="red" >Testing Text1</div>
<div class="red" >Testing Text2</div>

CSS

.red {
  color: red;
}
.green {
  color: green;
}

的Javascript

jQuery(document).ready(function(){
    jQuery(document).on('click',".red-btn",function (){
        alert("red color");
        jQuery(".green").removeClass("green").addClass("red");
    });
    jQuery(document).on('click',".green-btn",function (){
        alert("green color");
        jQuery(".red").removeClass("red").addClass("green");
    });
});

My Project DEMO

2 个答案:

答案 0 :(得分:0)

您可以使用jQuery cookie插件:https://github.com/carhartl/jquery-cookie

您的示例中的用法如下:

jQuery(document).ready(function(){

    //check if cookie has been set
    var cookieColor = $.cookie("selected_class");
    if (cookieColor) {
          //remove default "red" class and add cookie class
          $(".red").removeClass("red").addClass(cookieColor);
    }

    jQuery(document).on('click',".red-btn",function (){
        alert("red color");
         //store the value
         $.cookie("selected_class", "red");

        jQuery(".green").removeClass("green").addClass("red");
    });
    jQuery(document).on('click',".green-btn",function (){
        alert("green color");

         //store the value
         $.cookie("selected_class", "green");
        jQuery(".red").removeClass("red").addClass("green");
    });
});

答案 1 :(得分:0)

$('a[class*=btn]').click(function(){
    if($(this).hasClass('.red-btn'))
    {
        $(".green").removeClass("green").addClass("red");
        $.cookie("color-class", "red");
    }
    else if($(this).hasClass('.green-btn'))
    {
        $(".red").removeClass("red").addClass("green");
        $.cookie("color-class", "green");
    }
});