[英]Need Help in Creating a Cookie
I have a button named yes and another named no . 我有一个名为yes的按钮,另一个名为no的按钮。
<input type="button" name="yes" onclick="button()">
<input type="button" name="no">
I want to create a cookie when yes is clicked that would store the info "YES" and needs to expire after 7 days. 我想,当是被点击,将存储信息“YES”,并且需要7天后到期创建的cookie。 How do i do that?
我怎么做? The only information that the cookie needs to store is "YES".
Cookie需要存储的唯一信息是“是”。
You could use document.cookie : 您可以使用document.cookie :
var expDate = new Date();
expDate.setDate(expDate.getDate() + 7);
document.cookie = 'your_cookie_name=YES;expires=' + expDate.toUTCString();
Or if you are using jquery you may take a look at the Cookie plugin . 或者,如果您使用的是jquery,则可以查看Cookie插件 。 Here's an example .
这是一个例子 。
Here's what i use 这是我用的
var cookie = {
"create": function(name, value, days) {
if (typeof days !== 'number' || typeof name !== 'string' || typeof value !== 'string') {
return false;
}
var date = new Date();
date.setTime(date.getTime() + (days*86400000));
document.cookie = name + '=' + value + '; expires=' + date.toGMTString() + '; path=/';
},
"read": function(name) {
var cookie = document.cookie,
i, val = false;
cookie = cookie.split(';');
for (i = 0; i < cookie.length; i++) {
if (cookie[i].indexOf(name) !== -1) {
while (cookie[i].indexOf(name) > 0 && cookie[i].length > name.length) {
cookie[i] = cookie[i].substr(1);
}
val = cookie[i].substr(name.length + 1);
}
}
return val;
},
"erase": function(name) {
this.create(name, '', -1);
}
};
You can then use: 然后,您可以使用:
cookie.create("userName", "Bill", 7); // store userName "Bill" for 7 days.
cookie.read("userName"); // "Bill"
cookie.erase("userName");
Here's a fiddle to see how it works. 这是一个小玩意儿,看看它是如何工作的。 http://jsfiddle.net/robert/4vLT6/
http://jsfiddle.net/robert/4vLT6/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.