简体   繁体   中英

How can I check if a cookie has been set using jQuery?

I am using the following code:

$('#theme').attr('href', $.cookie("jquery-ui-theme"));

This works if the cookie has already been set. But how can I make a default href if the cookie has not yet been se

Strange to see suggestions here for a ternary operator in which the first value is the same as the condition. Shorten it to:

$('#theme').attr('href', $.cookie('jquery-ui-theme') || "default");

You can always reduce the ternary expression A ? A : B A ? A : B to the simpler A || B A || B

You could use a ternary operation which is essentially an if statement that fits on one line. They're structured as:

expression ? valueIfTrue : valueIfFalse;

I tend to use them for situations like this where you want a default value if something isn't set.

var href = $.cookie("jquery-ui-theme") ? $.cookie("jquery-ui-theme") : 'http://www.example.com';
$('#theme').attr('href', href);

This is equivalent to:

var href = $.cookie("jquery-ui-theme");
if (!href) {
    href = 'http://www.example.com';
}
$('#theme').attr('href', href);

I'm not familiar with your cookie plugin, but just use a ternary operator (and modify this code for your plugin if needed):

$('#theme').attr('href', ($.cookie('jquery-ui-theme')!='') ? $.cookie('jquery-ui-theme') : 'your-default-value'))

See also: Operator precedence with Javascript Ternary operator

Check if it exists:

if ($.cookie('jquery-ui-theme') != null) {
  $('#theme').attr('href', $.cookie("jquery-ui-theme"));
} else {
  $('#theme').attr('href', 'default');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM