本文翻译自:Set cookie and get cookie with JavaScript [duplicate]
This question already has an answer here: 这个问题已经在这里有了答案:
- How do I create and read a value from cookie? 如何创建和读取Cookie中的值? 17 answers 17个答案
I'm trying to set a cookie depending on which CSS file I choose in my HTML. 我试图根据我在HTML中选择的CSS文件来设置Cookie。 I have a form with a list of options, and different CSS files as values. 我有一个带有选项列表的表单,以及不同的CSS文件作为值。 When I choose a file, it should be saved to a cookie for about a week. 当我选择一个文件时,应将其保存到Cookie大约一周。 The next time you open your HTML file, it should be the previous file you've chosen. 下次打开HTML文件时,它应该是您选择的上一个文件。
JavaScript code: 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 code: 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>
#1楼
参考:https://stackoom.com/question/z99z/设置Cookie并使用JavaScript获取Cookie-重复
#2楼
Check JavaScript Cookies on W3Schools.com for setting and getting cookie values via JS. 在W3Schools.com上检查JavaScript Cookie,以通过JS设置和获取Cookie值。
Just use the setCookie and getCookie methods mentioned there. 只需使用那里提到的setCookie和getCookie方法。
So, the code will look something like: 因此,代码将类似于:
<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>
#3楼
These are much much better references than w3schools (the most awful web reference ever made): 这些参考比w3schools(有史以来最糟糕的网络参考) 要好得多:
- How cookies work (quirksmode.org) Cookie的工作方式(quirksmode.org)
- MDN document.cookie MDN document.cookie
Examples derived from these references: 从这些参考文献中得出的示例:
// sets the cookie cookie1
document.cookie =
'cookie1=test; expires=Fri, 19 Jun 2020 20:47:11 UTC; path=/'
// sets the cookie cookie2 (cookie1 is *not* overwritten)
document.cookie =
'cookie2=test; expires=Fri, 19 Jun 2020 20:47:11 UTC; path=/'
// remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'
The Mozilla reference even has a nice cookie library you can use. Mozilla参考文献甚至有一个不错的cookie库供您使用。
#4楼
I'm sure this question should have a more general answer with some reusable code that works with cookies as key-value pairs. 我确信这个问题应该有一个更通用的答案,其中包含一些可重复使用的代码,这些代码可将Cookie作为键值对使用。
This snippet is taken from MDN and probably is trustable. 该摘录取自MDN ,可能是可信的。 This is UTF-safe object for work with cookies: 这是用于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 has some tests to prove this works in all cases. Mozilla进行了一些测试,以证明此方法在所有情况下均有效。
There is an alternative snippet here : 还有一个另外的片段在这里 :
#5楼
I find the following code to be much simpler than anything else: 我发现以下代码比其他任何代码都简单得多:
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;';
}
Now, calling functions 现在,调用函数
setCookie('ppkcookie','testcookie',7);
var x = getCookie('ppkcookie');
if (x) {
[do something with x]
}
Source - http://www.quirksmode.org/js/cookies.html 来源-http: //www.quirksmode.org/js/cookies.html
They updated the page today so everything in the page should be latest as of now. 他们今天更新了页面,因此页面中的所有内容都应该是最新的。