javascript define cookie
Something very wrong is going on this piece of code:
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=es开发者_如何学Pythoncape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function checkCookie()
{
var username=getCookie("username");
if (username=="username"){
document.getElementById(mydivx).style.display = 'block'; }else{
document.getElementById(mydivx).style.display = 'none';
}
}
and a button to define the cookie:
<a href="#" onClick="setCookie("username",username,365); return true">esconder</a>
So this should be happening, if the button is clicked, it defines a cookie named "username" with the value "username", the getcookie function gets the cookie username and its value.
What am i doing wrong?
Hope you can help me guys !
EDIT: SOLUTION:
Just remove the ";" from the call, and add some single quotations to the code from the button:
esconder
Thanks to stealthyninja
In your HTML code, replace
<a href="#" onClick="setCookie("username",username,365); return true">esconder</a>
with
<a href="#" onClick="setCookie('username', 'username', 365); return false">esconder</a>
The return false
is so that your browser doesn't actually browse to the href
which would make a hash (#
) appear in your address bar. In other words, it's similar to preventing the default action of clicking on the link without JavaScript to prevent it.
Update
The second username
should be a variable or string. username
by itself is undefined.
your setcookie never got called I beleive try this:
<a href="#" onClick="setCookie('username',username,365); return true">esconder</a>
<a href="#" onClick="setCookie("username",username,365); return true">esconder</a>
You have an error in that code. onClick="" and "username"... Try:
<a href="#" onClick="setCookie('username','username',365);">esconder</a>
Not sure if this is all of it, but this line:
<a href="#" onClick="setCookie("username",username,365); return true">esconder</a>
Has a problem, since you're terminating the string. You're using double quotes inside double quotes; try
<a href="#" onClick="setCookie('username',username,365); return true">esconder</a>
精彩评论