如何在我的JavaScript中保存添加或删除类cookie

how to save add or remove classes cookies in my javascript?

本文关键字:添加 删除 cookie 保存 我的 JavaScript      更新时间:2023-09-26

我想在cookie中保存"active"类和"icon"类。怎么办?

.html

<div class="changeWrap">
        <span class="switch-male"><a href="javascript:"><i class="glyphicon glyphicon-unchecked"></i> Male</a></span>
        <span class="switch-female"><a href="javascript:" class="active"><i class="glyphicon glyphicon-check"></i><span> Female</span></a></span>
</div>

.css

.active{
    color: red;
}

演示:http://jsfiddle.net/deqzjefq/2/

首先创建你的cookie:

document.cookie="class=active;gender=male";

然后获取 cookie 的值(名称"类")

function getCookie(cname) {
    var name = cname + "=";
    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);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}

然后为锚标记提供 id

<div class="changeWrap">
        <span class="switch-male"><a href="javascript:" id='male-anchor'><i class="glyphicon glyphicon-unchecked"></i> Male</a></span>
        <span class="switch-female"><a href="javascript:" id='female-anchor'><i class="glyphicon glyphicon-check"></i><span> Female</span></a></span>
</div>

检查饼干性别:

var gender = getCookie('gender');
if(gender == 'male'{
    document.getElementsById('male-anchor').setAttribute("class", getCookie('class'));
}
else{
    document.getElementsById('female-anchor').setAttribute("class", getCookie('class'));
}

http://jsfiddle.net/k8pbp97k/1/