I want to add 'Year' or Years' to the end of a string depending on the string. Like this:
$("#selector").val(conditional_value_here);
Using jQuery UI I have a slider that manipulates a value:
$("#slider").slider({
value: 1,
min: 1,
max: 25,
step: 1,
slide: function(event, ui) {
$("#amount").val(ui.value + '开发者_运维技巧 Year' + function(){return (ui.value == 1) ? '' : 's';} );
}
});
// and again I want to do the same for the initialization of the value:
$("#amount_3").val($("#slider_3").slider("value") + ' Jahr' + function(){return ($("#slider_3").slider("value") == 1) ? '' : 's';});
This does not work. What is the correct way to to this?
As Reigel said, you can just use the ternary operator ? :
without requiring the function.
condition ? x : y;
If condition
is true, then x
is returned, otherwise y
is returned. When using it, just make sure to use parentheses liberally.
str = "This is " + numDays + numDays == 1 ? " day" : " days" + " old";
// no matter the value of numDays, the above always evaluates to " day"
// it is equivalent to:
str = ("This is " + numDays + numDays == 1) ? (" day") : (" days" + " old");
// instead, this is probably what was wanted:
str = "This is " + numDays + (numDays == 1 ? " day" : " days") + " old";
Alternatively, if you had a really really really good reason to do something like what you tried in your example, you could make it work like this:
$("#amount").val(
ui.value + ' Year' + (function(){return (ui.value == 1) ? '' : 's';})()
);
...but if I saw something like that in production, I'd be forced to hunt you down with a large axe.
just
$("#amount").val(ui.value + ' Year' + (ui.value == 1) ? '' : 's');
精彩评论