Reputation: 57129
In jQuery, can you do something like this:
function f(b) {
return $("<input></input>")
.addClass("test")
.if(b, function() {
$(this).attr("disabled", true).addClass("example");
})
.val("test");
}
instead of:
function f(b) {
var input = $("<input></input>").addClass("test");
if (b) {
input.attr("disabled", true).addClass("example");
}
return input.val("test");
}
?
It's just a syntactic sugar, actually. A useful one, though. Especially while authoring large Ajax applications.
Is this feature planned for next versions or something?
Upvotes: 0
Views: 52
Reputation: 236022
No, there is no "conditional" method or something. I don't think a method like that will make it into the core, it's pretty much like overkill isn't it? Example:
function f( b ) {
return $( '<input>', {
'class': 'test',
disabled: !!b, // alternate: b === 'something' ? true : false
value: 'test'
});
}
That would just bend that b
variable into a boolean value and pass it to the disable attribute
. I guess you can create similar construct on all occasions where such a method like .if()
could be useful.
Demo: http://jsfiddle.net/L8ZaP/
Upvotes: 1
Reputation: 9562
I think this doesn't look worse:
function f(b) {
return $("<input></input>")
.addClass("test")
.attr("disabled", b ? true : false)
.addClass(b ? "example" : "")
.val("test");
}
Upvotes: 1
Reputation: 78667
See this chainable iif plugin by Ben Alman.
Example
$('div')
.append( '1' )
.iff( my_test, 'foo' )
.append( '2' )
.end()
.append( '3' );
Another way is as a commentator to the above post explains here
Example
$(this)[$(this).hasClass("myClass")?"hide":"show"]();
Upvotes: 1