Home Ajax Jquery Understanding jQuery statement chaining
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Understanding jQuery statement chaining

Advertisement
This page discusses - Understanding jQuery statement chaining

Understanding jQuery statement chaining

     

Understanding jQuery statement chaining

JQuery provide statement chaining which can reduce the length of the code and reduce overhead of programmer.

In statement chaining , you can call multiple methods  in a single statement.

For example, you want to remove and assign a new css class to the div, you can do it like this :

$('div1').removeClass('oldClass').addClass('newClass');

Given below another example to select a column ,change it's color and append some text to it :

$('#Table1').find('.lastColumn').makeRed().append('changed');

Chainable 'if' statement using jQuery 'iff' :

'iff' works like 'filter', it allows us to process the subset of filtered element as well as you can add or remove individual elements without braking chain.

For example ,given below code append  some value to 'div' if provided value is equal to 'bar' . If not , it will append another value to it :

function compare( x ) {
return a === 'set';
}; 
$('div')
.append( '1' )
.iff( compare, 'select' )
.append( '2' )
.end()
.append( '3' );

Another example which are using two 'iff ' statements :

function my_callback( data ) {
$('<div/>')
.iff( data.success )
.append( '<img src="' + data.src + '"/>' )
.end()
.iff( data.error )
.append( 'An error has occurred.' )
.addClass( 'error' )
.end()
.appendTo( 'body' );
};

Chainable 'if-else' type statement in jQuery :

This code will first set the color of all links to blue, then append ??*?? to them. If k was set to anything else, the links would be colored red instead (and ??*?? would still be appended).

var k = 1;

$('a')
.cond(
k === 1, function(){
this.css({ color: 'purple' });
},
function(){
this.css({ color: 'red' });
}
)
.append( '*' );

Learn from experts! Attend jQuery Training classes.

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 18, 2011

Related Tutorials

Ask Questions?    Discuss: Understanding jQuery statement chaining  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com