Cookie的过期日期
我不是程序员。我正在尝试使用一个记录最后一个下拉菜单选项的cookie脚本。Cookie的过期日期
我发现了一个可行的脚本,但它只有一个会话cookie。如何在此脚本中向Cookie添加到期日期?
<head>
<script>
function SETcookie() {
document.cookie = "Selected=" + document.getElementById('myList').selectedIndex;
}
function GETcookie() {
if (document.cookie) {
eval(document.cookie);
document.getElementById('myList').selectedIndex = Selected;
}
}
</script>
</head>
<body onLoad="GETcookie()">
<select id="myList" onChange="SETcookie()">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
</body>
尝试
var a = new Date();
a = new Date(a.getTime() +1000*60*60*24*365);
document.cookie = 'mycookie=somevalue; expires='+a.toGMTString()+';';
PS。值1000 * 60 * 60 * 24 * 365 = 1年
获取所选指数试试这个的getCookie:
function GETcookie(){
if (document.cookie){
var a = document.cookie;
Selected = a.substring(a.search('Selected=')+9,a.search(';'));
alert("Selected = " + Selected);
document.getElementById('myList').selectedIndex=Selected;
}}
你可以试试这个:
function SETcookie(){
var validity_days = 7;
var expires = validity_days * 1000 * 60 * 60 * 24;
var expires_date = new Date(today.getTime() + (expires));
document.cookie="Selected="+document.getElementById('myList').selectedIndex + ";expires=" + expires_date.toGMTString() + ";";
}
“today”未定义,您的函数仅用于您自己的代码,因为它使用#myList DOM对象。这是越野车和无用的。 –
你是对的,'今天'没有在这里定义,但“myList”是来自问题的元素的ID,它不是他们刚才所做的。 –
试试这个:
function setCookie(c_name,c_value,exdays) {
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
document.cookie=encodeURIComponent(c_name)
+ "=" + encodeURIComponent(c_value)
+ (!exdays ? "" : "; expires="+exdate.toUTCString());
;
}
c_name
是cookie的名称
c_value
是cookie值
exdays
是你想要的饼干到期的天数后
越狱已弃用。你不应该使用它。顺便说一句,总是仔细检查w3schools的例子... –
这里的函数,它是100%的工作,并没有贬值功能。
function setCookie(variable, value, expires_seconds) {
var d = new Date();
d = new Date(d.getTime() + 1000 * expires_seconds);
document.cookie = variable + '=' + value + '; expires=' + d.toGMTString() + ';';
}
可能,这将有助于
document.cookie = "coolName"+ "=" +"coolValue"+ ";" + "expires="+ new Date(new Date().getTime()+60*60*1000*24).toGMTString()+";path=/";
这没有奏效。也许我把它放在一个错误的地方。你能告诉我它应该如何在这里http://jsfiddle.net/BrUmu/ –
只需在你的SETcookie函数中设置它。你得到了什么? – CloudyMarble
我做了,cookies完全停止工作。在这里查看更新http://jsfiddle.net/BrUmu/1/ –