gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:55:33 24 4
gpt4 key购买 nike

我想在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com