我试图根据我在HTML中选择的CSS文件来设置Cookie。我有一个带有选项列表的表单,以及不同的CSS文件作为值。当我选择一个文件时,应将其保存到Cookie大约一周。下次打开HTML文件时,它应该是您选择的上一个文件。
JavaScript代码:
function cssLayout() { document.getElementById("css").href = this.value; } function setCookie(){ var date = new Date("Februari 10, 2013"); var dateString = date.toGMTString(); var cookieString = "Css=document.getElementById("css").href" + dateString; document.cookie = cookieString; } function getCookie(){ alert(document.cookie); }
HTML代码:
<form> Select your css layout:<br> <select id="myList"> <option value="style-1.css">CSS1</option> <option value="style-2.css">CSS2</option> <option value="style-3.css">CSS3</option> <option value="style-4.css">CSS4</option> </select> </form>
我发现以下代码比其他任何代码都简单得多:
function setCookie(name,value,days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days*24*60*60*1000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + (value || "") + expires + "; path=/"; } function getCookie(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) { document.cookie = name+'=; Max-Age=-99999999;'; }
现在,调用函数
setCookie('ppkcookie','testcookie',7); var x = getCookie('ppkcookie'); if (x) { [do something with x] }