javascript - 如何在我的 javascript 中保存添加或删除类 cookie?

标签 javascript jquery css cookies

我想在 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的值(名称'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 "";
}

然后给 anchor 标签赋予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/

关于javascript - 如何在我的 javascript 中保存添加或删除类 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27143240/

相关文章:

html - 为什么我的 jQueryMobile CSS 样式被应用到链接页面?

javascript - Bootstrap "Panel-collapse" "collapse"无法在线工作

javascript - 手动隐藏后的 Bootstrap 模态错误

javascript - nuxtjs中如何控制路由渲染

javascript - 在 HTML/CSS/JavaScript 中创建可点击区域

javascript - 未捕获的类型错误 : undefined is not a function (on video pause function)

html - 将图像设置为网页的背景(屏幕宽度)

javascript - D3.js 中的 array_replace?

javascript - Safari 中使用数据表的 Excel 按钮问题

jquery - 切换第一行文本末尾的箭头