【问题标题】:how to save add or remove classes cookies in my javascript?如何在我的 javascript 中保存添加或删除类 cookie?
【发布时间】:2014-11-26 15:41:17
【问题描述】:

我想在 cookie 中保存“活动”类和“图标”类。怎么办?

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 中保存活动类和图标类是什么意思?你想达到什么目的
  • 我真的明白你的问题是什么。您想将活动类名(如“switch-female”)或完整的跨度标签保存到 cookie 中吗?如果是的话,我能知道你为什么想要那个吗?

标签: javascript jquery css cookies


【解决方案1】:

首先创建你的cookie:

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

然后获取cookie的值(名称'class')

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>

检查 cookie 性别:

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/

【讨论】:

    猜你喜欢
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 2015-09-16
    • 2013-07-08
    • 2023-03-07
    • 2022-01-22
    相关资源
    最近更新 更多