这些方面的东西应该适合你。在 javascripter.net 上的一篇文章Setting a Cookie from JavaScript中找到了通过 javascript 创建 cookie 的功能
。
HTML:
<select id="ThemeSelect" onchange="setCookie('theme', this.value, 365);">
<option value="zelda">Zelda</option>
<option value="smb2">SMB 2</option>
</select>
Javascript:
function setCookie(cookieName, cookieValue, nDays) {
var today = new Date();
var expire = new Date();
if (!nDays)
nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
}
编辑:
保存 cookie
我已为您将这两个功能合二为一。
HTML:
<select id="ThemeSelect" onchange="saveTheme(this.value);">
<option value="zelda">Zelda</option>
<option value="smb2">SMB 2</option>
</select>
Javascript:
var saveclass = null;
function saveTheme(cookieValue)
{
var sel = document.getElementById('ThemeSelect');
saveclass = saveclass ? saveclass : document.body.className;
document.body.className = saveclass + ' ' + sel.value;
setCookie('theme', cookieValue, 365);
}
function setCookie(cookieName, cookieValue, nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0)
nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
}
现场演示
返回页面时读取 cookie
感谢邓斯莫尔布
我们可以使用这个功能获取cookie,无耻地从这个问题中窃取。
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;
}
然后我们需要在页面加载时选择值。下面的代码将实现这一点:
document.addEventListener('DOMContentLoaded', function() {
var themeSelect = document.getElementById('ThemeSelect');
var selectedTheme = readCookie('theme');
themeSelect.value = selectedTheme;
saveclass = saveclass ? saveclass : document.body.className;
document.body.className = saveclass + ' ' + selectedTheme;
});
现场演示