我正在使用以下代码:
$('#theme').attr('href', $.cookie("jquery-ui-theme"));
如果 cookie 已设置,则此方法有效。但是,如果 cookie 尚未设置,我该如何设置默认的 href
我正在使用以下代码:
$('#theme').attr('href', $.cookie("jquery-ui-theme"));
如果 cookie 已设置,则此方法有效。但是,如果 cookie 尚未设置,我该如何设置默认的 href
奇怪的是在这里看到关于第一个值与条件相同的三元运算符的建议。将其缩短为:
$('#theme').attr('href', $.cookie('jquery-ui-theme') || "default");
您总是可以将三元表达式A ? A : B
简化为更简单的A || B
您可以使用三元运算,它本质上是一条适合一行的 if 语句。它们的结构如下:
表达 ?valueIfTrue : valueIfFalse;
我倾向于将它们用于此类情况,如果未设置某些内容,则需要默认值。
var href = $.cookie("jquery-ui-theme") ? $.cookie("jquery-ui-theme") : 'http://www.example.com';
$('#theme').attr('href', href);
这相当于:
var href = $.cookie("jquery-ui-theme");
if (!href) {
href = 'http://www.example.com';
}
$('#theme').attr('href', href);
我不熟悉您的 cookie 插件,但只需使用三元运算符(并在需要时为您的插件修改此代码):
$('#theme').attr('href', ($.cookie('jquery-ui-theme')!='') ? $.cookie('jquery-ui-theme') : 'your-default-value'))
另请参阅: Javascript 三元运算符的运算符优先级
检查它是否存在:
if ($.cookie('jquery-ui-theme') != null) {
$('#theme').attr('href', $.cookie("jquery-ui-theme"));
} else {
$('#theme').attr('href', 'default');
}