如何删除现有的类名并添加一个带有jQuery和cookie的新名称? [英] How do I remove an existing class name and add a new one with jQuery and cookies?

查看:77
本文介绍了如何删除现有的类名并添加一个带有jQuery和cookie的新名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何删除类名并将其替换为新名称?

How can you remove a class name and replace it with a new one?

<style>
    .red {background-color: #FF0000;}
    .green{background-color: #00FF00;}
    .blue {background-color: #0000FF;}
</style>

<body class="red">
    <ul>
        <li><a href="">red</a></li>
        <li><a href="">green</a></li>
        <li><a href="">blue</a></li>
    </ul>
</body>

在这种情况下,当您点击红色或绿色或蓝色时,身体类名称将相应更改。它还会创建一个cookie来保存选择。

In this case when you click on red or green or blue, the body class name will change accordingly. Also it will make a cookie which will save the choice.

我尝试了jQuery .addClass并且它正在工作,但是它在现有的类之上添加了一个类。此外,我无法保存cookie。

I tried the jQuery .addClass and it's working, but it's adding a class on top of the existing one. Also I can't manage to save the cookie.

推荐答案

使用:

$('.red').removeClass('red').addClass('blue');

这是完整的工作代码

$(function() {
    $("a").click(function() {
        var color = $(this).text();
        $("body").removeClass().addClass(color);
        return false;
    });
});

现在为cookie部分

And now for the cookie part

$(function() {
    $("a").click(function() {
        var color = $(this).text();
        $("body").removeClass().addClass(color);
        createCookie("color",color);
        return false;
    });

    if (readCookie("color") != null) {
      $("body").removeClass().addClass(readCookie("color"));

    }
    else {
      $("body").removeClass().addClass("red");
    }
});

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else
        var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
    }

    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ')
                c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0)
                return c.substring(nameEQ.length,c.length);
        }
        return null;
    }

    function eraseCookie(name) {
    createCookie(name,"",-1);
}

这里的工作示例。感谢 QuirksMode 了解预制的cookie代码(cookie-cutter cookie代码) ?)

Working example here. A thank you to QuirksMode for the pre-made cookie code (cookie-cutter cookie code?)

这篇关于如何删除现有的类名并添加一个带有jQuery和cookie的新名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆