我想在 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;
}
最佳答案
首先为您创建 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'));
}
关于javascript - 如何在我的 javascript 中保存添加或删除类 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27143240/