2012-02-26 74 views

回答

1

你可以使用ternary operation这本质上是一条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); 
0

我不熟悉您的Cookie插件,但只使用一个三元操作符(如果需要修改这个代码给你的插件):

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

参见:如果存在Operator precedence with Javascript Ternary operator

0

检查:

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

奇怪的是,在这里看到一个三元运算符的建议,其中第一个值与条件相同。缩短到:

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

你总是可以减少三元表达A ? A : B更简单的A || B

+2

另外请注意,这不是特别相关的jQuery的饼干插件,但默认值的通用解决方案 – migg 2012-10-23 17:08:40

相关问题