我正在尝试使用简单的IF语句来检查特定的Cookie是否存在: 我不打算将任何简单的东西复杂化,比如
if (document.cookie.name("a") == -1 {
console.log("false");
else {
console.log("true");
}
这是什么语法?
答案 0 :(得分:0)
也许这可以提供帮助(w3schools关于javascript cookies的文档):
https://www.w3schools.com/js/js_cookies.asp
获取Cookie的功能
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
答案 1 :(得分:0)
首先:
function getCookie(name) {
var cookies = '; ' + document.cookie;
var splitCookie = cookies.split('; ' + name + '=');
if (splitCookie.lenght == 2) return splitCookie.pop();
}
然后你可以使用你的if语句:
if (getCookie('a'))
console.log("false");
else
console.log("true");
应该有效。
答案 2 :(得分:0)
这可以帮到你:
class Cookies {
static exists(name) {
return name && !!Cookies.get(name);
}
static set(name, value, expires = Date.now() + 8.64e+7, path = '/') {
document.cookie = `${name}=${value};expires=${expires};path=${path};`;
}
static get(name = null) {
const cookies = decodeURIComponent(document.cookie)
.split(/;\s?/)
.map(c => {
let [name, value] = c.split(/\s?=\s?/);
return {name, value};
})
;
return name
? cookies.filter(c => c.name === name).pop() || null
: cookies
;
}
}