jQuery: if_() ... else_()
if_()
... else_()
is a tiny jQuery plugin that provides simple flow-control for jQuery chains.
jQuery.fn.extend({
if_: function (cond)
{
if (jQuery.isFunction(cond)) { cond = cond.call(this); }
this.if_CondMet = !!cond;
return this.pushStack(cond ? this : []);
},
else_: function (cond)
{
var _this = this.end();
return _this.if_CondMet ?
_this.pushStack([]):
_this.if_(arguments.length ? cond : 1);
}
});
Here's an example of how the plugin can be used using a boolean value as a condition:
jQuery('ul')
.if_( cfg.addItem )
.append('<li>Last Item</li>')
.else_()
.addClass('untouched')
.end();
Functions may also be passed as condition, and the else_()
method doubles as an "else if
" when passed a condition.
jQuery('ul')
.if_( function(){ return this.find('>li').length % 2; } )
.addClass('oddNumbered')
.else_( cfg.addItem ) // else if
.append('<li>Last Item</li>')
.addClass('oddNumbered')
.else_()
.addClass('untouched')
.end();
Having these methods at your disposal makes jQuery chains feel even more like a true meta-programming language.
Enjoy!
Nýleg svör frá lesendum