Jquery: set get cookie, apply as class
I want to set a cookie when a person clicks on a link, then i want to get that cookie and have it somehow add the class 'pinned' to '#navigation'. I'm not too sure if this is right, i'm using the jquery cookie plugin, ugh. this is the code I have so far:
to set the cookie:
$.cookie('CookieName':'#navigation');
gets the cookie, a开发者_开发知识库dds the class 'pinned' onto the element #navigation
$("#" + $.cookie('cookieName')).addClass("pinned");
But whenever i put this code anywhere in my JS file, it causes all of the JS not to work anymore, so it breaks my whole page.
You can store a value in a cookie, but you can't attribute a class (or id) to one (although obviously you can name a cookie, but it's not quite the same thing). You could, instead, do something like this:
$.cookie('class','pinned',{expires:30});
and then retrieve the value:
var pinnedClass = $.cookie('class');
$('#navigation').addClass(pinnedClass);
You have a syntax error while setting the cookie, and you're also retrieving the cookie with the wrong spelling:
$.cookie('CookieName', 'navigation');
$("#" + $.cookie('CookieName')).addClass("pinned");
you can use normal javacsript code to get the cookie like below.. the following code should work
this.getCookie = function(name) {
if (document.cookie.length > 0) {
start = document.cookie.indexOf(name + "=");
if (start != -1) {
start = start + name.length + 1;
end = document.cookie.indexOf(";", start);
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(start, end));
}
}
return "";
精彩评论