[英]How do I remove an 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>
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.
它还会制作一个可以节省选择的cookie。
I tried the jQuery .addClass and it's working, but it's adding a class on top of the existing one. 我尝试了jQuery .addClass并且它正在工作,但是它在现有的类之上添加了一个类。 Also I can't manage to save the cookie.
此外,我无法保存cookie。
Use: 采用:
$('.red').removeClass('red').addClass('blue');
Here's the full working code : 这是完整的工作代码 :
$(function() {
$("a").click(function() {
var color = $(this).text();
$("body").removeClass().addClass(color);
return false;
});
});
And now for the cookie part 现在为cookie部分
$(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);
}
Working example here . 这里的工作示例 。 A thank you to QuirksMode for the pre-made cookie code (cookie-cutter cookie code?)
感谢QuirksMode预先制作的cookie代码(cookie-cutter cookie代码?)
Without jQuery you can do this with a line as simple as: 如果没有jQuery,您可以使用以下简单的行来完成此操作:
document.getElementsByTagName("body")[0].className = "red";
This effectively removes the class assigned to the element and replace it with whatever you want. 这有效地删除了分配给元素的类,并将其替换为您想要的任何内容。
For cookies, PPK has a few simple methods to read/write/erase cookies . 对于cookie, PPK有一些简单的方法来读/写/删除cookie 。
createCookie("mySiteCookie", "red", 7); // Set the cookie to expire in 7 days.
readCookie("mySiteCookie"); // Should yield "red"
你还需要removeClass 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.