Pil*_*lan -1 javascript cookies
通过JavaScript获取和设置Cookie有点像这样:
组: document.cookie = "<key>=<value>[;expires=<utc_expires>[;path=<path>]]";
获取:解析document.cookie
我在W3C.org Cookies上找到了此获取和设置功能
有没有更优雅/简单的方法可以做到这一点?
小智 8
您可以使用一些简单的功能,例如setCookie()
和getCookie()
。
您可以使用调用设置Cookie:
setCookie('myName','value', 3);
Run Code Online (Sandbox Code Playgroud)
setCookie('myName','value', 3);
Run Code Online (Sandbox Code Playgroud)
注意:来源来自quirksmode。如果您想了解有关Cookie的更多信息,请查看文档。
小智 6
ES6的做法是:
const setCookie = (cookieKey, cookieValue, expirationDays) => {
let expiryDate = '';
if (expirationDays) {
const date = new Date();
date.setTime(`${date.getTime()}${(expirationDays || 30 * 24 * 60 * 60 * 1000)}`);
expiryDate = `; expiryDate=" ${date.toUTCString()}`;
}
document.cookie = `${cookieKey}=${cookieValue || ''}${expiryDate}; path=/`;
}
const getCookie = (cookieKey) => {
let cookieName = `${cookieKey}=`;
let cookieArray = document.cookie.split(';');
for (let cookie of cookieArray) {
while (cookie.charAt(0) == ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(cookieName) == 0) {
return cookie.substring(cookieName.length, cookie.length);
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10734 次 |
最近记录: |