我有一个按钮名为是的和另一个名为没有。需要帮助创建一个Cookie
<input type="button" name="yes" onclick="button()">
<input type="button" name="no">
我想在是被点击,将存储信息“YES”,并且需要7天后到期创建的cookie。我怎么做? cookie需要存储的唯一信息是“YES”。
我有一个按钮名为是的和另一个名为没有。需要帮助创建一个Cookie
<input type="button" name="yes" onclick="button()">
<input type="button" name="no">
我想在是被点击,将存储信息“YES”,并且需要7天后到期创建的cookie。我怎么做? cookie需要存储的唯一信息是“YES”。
你可以使用document.cookie:
var expDate = new Date();
expDate.setDate(expDate.getDate() + 7);
document.cookie = 'your_cookie_name=YES;expires=' + expDate.toUTCString();
或者,如果你正在使用jQuery你可以看看的Cookie plugin。这是一个example。
这里是我使用
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);
}
};
然后,您可以使用:
cookie.create("userName", "Bill", 7); // store userName "Bill" for 7 days.
cookie.read("userName"); // "Bill"
cookie.erase("userName");
这里有一个小提琴,看看它是如何工作的。 http://jsfiddle.net/robert/4vLT6/
惊人的...它的工作。谢谢 – ryan 2010-11-13 16:53:54
最后,我如何阅读cookie? – ryan 2010-11-13 16:54:14
以字符串形式读取document.cookie。它将具有诸如“userName = Bill; favoriteColor = Red;时区= GMT”的值。用户名/最喜欢的颜色和时区是不同的饼干,所以解析字符串你喜欢怎么得到你想要的。 – Robert 2010-11-13 16:56:58