我想知道用户是否第一次访问我的网页。我目前正在将一个变量存储在本地存储中,并检查它是否为null,但它似乎在Internet Explorer中不起作用。我可以用什么方法来实现这个目标?
var str_count = localStorage.getItem("count");
if (str_count == null || str_count == "null")
{
// Do something
}
答案 0 :(得分:1)
您可以使用
设置Cookiedocument.cookie = name + "=" + value + "; expires=" + exp + "; path=/";
答案 1 :(得分:1)
使用cookie
设置localStorage
使用function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
肯定比使用旧版浏览器尚不支持更长。
检查此代码:
{{1}}
详细了解Cookie here。
答案 2 :(得分:0)
正如@Greg所说,更好的解决方案是设置和获取cookie值。这有两个功能:
setCookie = function(){
var args = arguments,
name = (args[0] ? args[0] : '') + '=',
_value = args[1] ? escape(args[1]) : '',
value = _value + ';',
expires = args[2] ? 'expires=' + args[2].toUTCString() + ';' : '',
path = args[3] ? 'path=' + args[3] + ';' : '',
domain = args[4] ? 'domain=' + args[4] + ';' : '',
secure = args[5] ? 'secure;' : '',
newCookie = name + value + expires + path + domain + secure;
document.cookie = newCookie.match(/[a-z||A-Z]/) ? newCookie : ''
return _value;
},
getCookie = function(name){
if(!name || name.replace(/[^a-z|0-9|çáéíóúãõâêîôûàèìòùäëïöü]/,'')=='*') return document.cookie;
var ck = ' ' + document.cookie + ' ',
pos = ck.search(' ' + name + '='),
pos = (pos!=-1) ? pos + 1 : ck.length,
ck = ck.substring(pos-1,ck.length),
end = (ck.search('; ')!=-1) ? ck.search('; ') : ck.length,
value = ck.substring(((ck.search('=')!=-1) ? (ck.search('=')+1) : end),end);
return unescape((value[value.length-1]==' ') ? value.substring(0,value.length-1) : value);
}
它们是交叉浏览器功能。要使用getCookie
功能,只需使用name
参数,使用setCookie
功能,使用name,value,expires,path,domain,secure
参数