Javascript 检查cookie是否存在且不工作
我使用下面的代码检查是否存在具有特定值的cookie,然后执行一些操作Javascript 检查cookie是否存在且不工作,javascript,jquery,cookies,Javascript,Jquery,Cookies,我使用下面的代码检查是否存在具有特定值的cookie,然后执行一些操作 $(document).ready(function() { if (document.cookie.indexOf('samplename=itsvalue')== -1 ) { alert("cookie"); } }); 无论cookie是否存在,它始终显示警报。我做错了什么?原始回答: 除非您有一个密钥为“samplename=itsvalue”的cookie,否则代码的计算结果将始终为tr
$(document).ready(function() {
if (document.cookie.indexOf('samplename=itsvalue')== -1 ) {
alert("cookie");
}
});
无论cookie是否存在,它始终显示警报。我做错了什么?原始回答:
除非您有一个密钥为“samplename=itsvalue”的cookie,否则代码的计算结果将始终为true。如果键为“samplename”,值为“itsvalue”,则应按如下方式重写检查:
if (document.cookie.indexOf('samplename') == -1 ) {
alert("cookie");
}
这将告诉您cookie不存在
要查看它是否存在:
if (document.cookie.indexOf('samplename') > -1 ) {
alert("cookie exists");
}
更新以更好地解决此问题:
您在该检查中查找的内容将始终评估为true并抛出警报。将以下函数添加到js并调用它来检查cookie是否存在
function getCookie(name) {
var cookie = document.cookie;
var prefix = name + "=";
var begin = cookie.indexOf("; " + prefix);
if (begin == -1) {
begin = cookie.indexOf(prefix);
if (begin != 0) return null;
} else {
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = cookie.length;
}
}
return unescape(cookie.substring(begin + prefix.length, end));
}
然后,您可以使用以下内容检查cookie:
var myCookie = getCookie("samplename");
if (myCookie == null) {
alert("cookie does not exist");
} else {
alert("cookie exists");
}
var cookies=document.cookie.split(“;”)//包含所有的cookies
var cookieName=[];//包含所有Cookie的名称
对于(i=0;i-1){
console.log(“存在”);
}否则{
console.log(“不存在”);
}
将此代码粘贴到浏览器控制台并检查。谢谢您的回答和更新!我真的很感激。我使用您以前的代码(在更新之前)进行了测试,它工作得非常好,再次感谢您。我将把这当作一个公认的答案,因为它解决了我的问题。如果您在新代码的旁边再次添加以前的代码,作为具有相同问题的任何人的替代解决方案,可能会更好。这里是
if(document.cookie.indexOf('samplename')>-1){alert(“cookie”);}
问候语@JerryB我将把以前的代码添加回。很高兴它对您有效。dc未定义
var cookies = document.cookie.split(';');//contains all the cookies
var cookieName = []; // to contain name of all the cookies
for(i=0;i<cookies.length;i++) {
cookieName[i] = cookies[i].split('=')[0].trim();
}
if(cookiesName.indexOf(cookieNameYouAreLookingFor)>-1) {
console.log("EXISTS");
} else {
console.log("DOESN'T EXIST");
}