我使用下面的代碼:如何檢查cookie是否使用jQuery設置?
$('#theme').attr('href', $.cookie("jquery-ui-theme"));
如果cookie已經設置這工作。但是,如果cookie尚未被使用,我怎麼能做一個默認的href
我使用下面的代碼:如何檢查cookie是否使用jQuery設置?
$('#theme').attr('href', $.cookie("jquery-ui-theme"));
如果cookie已經設置這工作。但是,如果cookie尚未被使用,我怎麼能做一個默認的href
你可以使用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);
我不熟悉您的Cookie插件,但只使用一個三元操作符(如果需要修改這個代碼給你的插件):
$('#theme').attr('href', ($.cookie('jquery-ui-theme')!='') ? $.cookie('jquery-ui-theme') : 'your-default-value'))
檢查:
if ($.cookie('jquery-ui-theme') != null) {
$('#theme').attr('href', $.cookie("jquery-ui-theme"));
} else {
$('#theme').attr('href', 'default');
}
奇怪的是,在這裏看到一個三元運算符的建議,其中第一個值與條件相同。縮短到:
$('#theme').attr('href', $.cookie('jquery-ui-theme') || "default");
你總是可以減少三元表達A ? A : B
更簡單的A || B
另外請注意,這不是特別相關的jQuery的餅乾插件,但默認值的通用解決方案 – migg 2012-10-23 17:08:40