如何删除现有的类名和添加一个新的一个jQuery和Cookie? [英] How to remove existing class name and add a new one with jQuery and Cookies?
问题描述
如何删除类名称并将其替换为新名称。
How can you remove a class name and replace it with a new one.
<style>
.red {background-color: #FF0000;}
.green{background-color: #00FF00;}
.blue {background-color: #0000FF;}
</style>
<body class="red">
<ul>
<li><a href="">red</a></li>
<li><a href="">green</a></li>
<li><a href="">blue</a></li>
</ul>
</body>
在这种情况下,当您单击红色或绿色或蓝色时,主体类名称将相应地更改。此外,它会使一个cookie,将保存的选择。
我尝试了jquery .addClass和它的工作,但它添加类在现有的顶部。我也不能保存cookie。
再次感谢。
In this case when you click on red or green or blue, the body class name will change accordingly. Also it will make a cookie which will save the choice. I tried the jquery .addClass and its working but its adding class on top of the existing one. Also I cann’t mange to save the cookie. Thank you again.
推荐答案
$('.red').removeClass('red').addClass('blue');
$(function() {
$("a").click(function() {
var color = $(this).text();
$("body").removeClass().addClass(color);
return false;
});
});
现在的cookie部分
And now for the cookie part
$(function() {
$("a").click(function() {
var color = $(this).text();
$("body").removeClass().addClass(color);
createCookie("color",color);
return false;
});
if (readCookie("color") != null) {
$("body").removeClass().addClass(readCookie("color"));
}
else {
$("body").removeClass().addClass("red");
}
});
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
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,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
这里的工作示例。感谢您对 QuirksMode 预先建立的Cookie代码(Cookie修补程序Cookie代码?)
Working example here. A thank you to QuirksMode for the pre-made cookie code (cookie-cutter cookie code?)
这篇关于如何删除现有的类名和添加一个新的一个jQuery和Cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!