作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想在 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/
我是一名优秀的程序员,十分优秀!