设置Cookie并获取Cookie与JavaScript

我试图设置一个cookie取决于我在我的Html中select的CSS文件。 我有一个选项列表和不同的CSS文件作为值的forms。 当我select一个文件,它应该被保存到一个cookie大约一个星期。 下一次你打开你的html文件,它应该是你select的以前的文件。

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 createCookie(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 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); } 

现在,调用函数

 createCookie('ppkcookie','testcookie',7); var x = readCookie('ppkcookie') if (x) { [do something with x] } 

来源 – http://www.quirksmode.org/js/cookies.html

他们今天更新了页面,所以页面中的所有内容都应该是最新的。

这些是比w3schools更好的参考(有史以来最糟糕的Web参考):

  • cookies如何工作(quirksmode.org)
  • MDN document.cookie

从这些参考派生的例子:

 // sets the cookie cookie1 document.cookie = 'cookie1=test; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/' // sets the cookie cookie2 (cookie1 is *not* overwritten) document.cookie = 'cookie2=test; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/' // remove cookie2 document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/' 

Mozilla的参考甚至有一个很好的cookie库,你可以使用。

我敢肯定,这个问题应该有一个更一般的答案,一些可重用的代码与cookie作为键值对。

这段代码取自MDN ,可能是值得信赖的。 这是使用cookie工作的UTF安全对象:

 var docCookies = { getItem: function (sKey) { return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null; }, setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) { if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; } var sExpires = ""; if (vEnd) { switch (vEnd.constructor) { case Number: sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd; break; case String: sExpires = "; expires=" + vEnd; break; case Date: sExpires = "; expires=" + vEnd.toUTCString(); break; } } document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : ""); return true; }, removeItem: function (sKey, sPath, sDomain) { if (!sKey || !this.hasItem(sKey)) { return false; } document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : ""); return true; }, hasItem: function (sKey) { return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }, keys: /* optional method: you can safely remove it! */ function () { var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/); for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); } return aKeys; } }; 

Mozilla有一些testingcertificate在所有情况下都能正常工作。

这里有一个替代片段:

检查W3Schools.com上的JavaScript Cookie,通过JS设置和获取cookie值。

只需使用那里提到的setCookie和getCookie方法。

所以,代码看起来像这样:

 <script> function setCookie(c_name, value, exdays) { var exdate = new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString()); document.cookie = c_name + "=" + c_value; } function getCookie(c_name) { var i, x, y, ARRcookies = document.cookie.split(";"); for (i = 0; i < ARRcookies.length; i++) { x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("=")); y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1); x = x.replace(/^\s+|\s+$/g, ""); if (x == c_name) { return unescape(y); } } } function cssSelected() { var cssSelected = $('#myList')[0].value; if (cssSelected !== "select") { setCookie("selectedCSS", cssSelected, 3); } } $(document).ready(function() { $('#myList')[0].value = getCookie("selectedCSS"); }) </script> <select id="myList" onchange="cssSelected();"> <option value="select">--Select--</option> <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>