<script type="text/javascript">
function WorldwideSellingModelCookie(){
days=7;
myDate = new Date();
myDate.setTime(myDate.getTime()+(days*24*60*60*1000));
document.cookie = 'WorldwideSellingModelCookie=Accepted; expires=' + myDate.toGMTString();
}
function CheckCookies(){
var worldwideSellingCookie = getCookie("WorldwideSellingModelCookie");
if (worldwideSellingCookie == "Accepted")
{
jQuery(".alert-worldwide").hide();
}
}
CheckCookies();
</script>
您好,
正在创建cookie,我只是不确定如何让我的if语句在我的CheckCookies函数中工作,以便它隐藏页面上的div?
我收到以下控制台错误:
未捕获的ReferenceError:未定义getCookie
有人可以告诉我做错了吗?
由于
更新
<script type="text/javascript">
function WorldwideSellingModelCookie(){
days=7;
myDate = new Date();
myDate.setTime(myDate.getTime()+(days*24*60*60*1000));
document.cookie = 'WorldwideSellingModelCookie=Accepted; expires=' + myDate.toGMTString();
}
function getCookie(cname) {
var name = cname + "=";
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);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length,c.length);
}
}
return "";
}
function CheckCookies(){
var worldwideSellingCookie = getCookie("WorldwideSellingModelCookie");
if (worldwideSellingCookie == "Accepted")
{
jQuery(".alert-worldwide").hide();
}
}
CheckCookies();
</script>
刚刚添加了检查cookie的功能,现在似乎正在工作,但是在隐藏之前div会暂时显示。有没有办法阻止这种情况发生?
答案 0 :(得分:5)
这些是我用来在JavaScript中添加,获取或清除cookie的函数。
/* function creates cooke with random key */
function setCookie(inputs) {
/* cookie name */
var name = (inputs[0]) ? inputs[0] : "key" + document.cookie.length;
/* cookie expire in 120 seconds */
var date = new Date();
date.setTime(date.getTime() + (120 * 1000));
var expires = "; expires=" + date.toGMTString();
/* sets cookie */
document.cookie = name + "=" + inputs[1] + expires;
};
/* get the cookie based on input */
function getCookie(input) {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var name = cookies[i].split('=')[0].toLowerCase();
var value = cookies[i].split('=')[1].toLowerCase();
if (name === input) {
return value;
} else if (value === input) {
return name;
}
}
return "";
};
/* destroy me cookies (well only delete javascript cookies) */
function clearCookies(elements) {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf('=');
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
$(elements[0]).val('');
$(elements[1]).val('');
$(elements[2]).val('');
$(elements[3]).html('No Cookie');
};
这也是一个很好的Document.cookie MDN