我不想在页面加载后更改课程。如何在我的项目中添加类cookie。
HTML 红色 绿色
<div class="red">Testing Text1</div>
<div class="red">Testing Text2</div>
CSS
.red{
color: red;
font-weight: bold;
}
.green {
color: green;
font-weight: bold;
}`
的Javascript
function changeClass(value) {
var color1 = 'red';
var color2 = 'green';
if (value == 2) {
color1 = 'green';
color2 = 'red';
};
var elems = document.getElementsByClassName(color1);
var i = elems.length;
while (i--) {
var item = elems[i];
if (hasClass(item, color1)) {
removeClass(item, color1);
addClass(item, color2);
}
};
return false;
};
function hasClass(ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
function addClass(ele, cls) {
if (!hasClass(ele, cls)) ele.className += " " + cls;
}
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ');
}
}
答案 0 :(得分:0)
用于在JS中添加Cookie
function setCookie(cname, cvalue, exdays)
{
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
在jS中获取Cookie
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 "";
}
现在,您可以在代码中的任何位置使用此功能并调用它。