最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery Cookies Creation...Check if cookie already has a value - Stack Overflow

programmeradmin1浏览0评论

I am using this code to create a cookie with JQuery:

$.cookie('MyCookieName', 'myValueHere');

It works fine but as I have the value assign to a random number it's generating a new one every reload.

What I need to do is check if cookie has a value and if it's not empty then don't create a new one or generate any new value.

I am using this code to create a cookie with JQuery:

$.cookie('MyCookieName', 'myValueHere');

It works fine but as I have the value assign to a random number it's generating a new one every reload.

What I need to do is check if cookie has a value and if it's not empty then don't create a new one or generate any new value.

Share Improve this question edited Feb 3, 2012 at 11:43 Manse 38.1k11 gold badges86 silver badges111 bronze badges asked Feb 3, 2012 at 11:40 Satch3000Satch3000 49.5k90 gold badges225 silver badges349 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2
if ($.cookie('MyCookieName') == null) {
    $.cookie('MyCookieName','MyCookieValue');
}

You can also add expire time and path in options.

$.cookie('MyCookieName','MyCookieValue', { path: '[path here]', expires: [days] });

Then you can be sure, that cookies won't be deleted.

Try checking for a value already set in an if statement like this

if($.cookie('MyCookieName') == null) {
   //it doesnt exist
} else {
   // do something else maybe
}

Thats if your plugin for example this one returns null when the cookie is not found

to avoid misunderstandings it's better to use exact parison:

if($.cookie('MyCookieName') === null) { //some stuff }
发布评论

评论列表(0)

  1. 暂无评论