2012-02-26 61 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