12.07.2015 Views

Pro JavaScript for Web Apps pdf - EBook Free Download

Pro JavaScript for Web Apps pdf - EBook Free Download

Pro JavaScript for Web Apps pdf - EBook Free Download

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 2 GETTING STARTEDListing 2-6. Chaining jQuery Method Calls...$(document).ready(function() {$('#buttonDiv input:submit').hide();$('Submit Order').appendTo("#buttonDiv").addClass("button");})...Notice how I have simply added the call to the addClass method to the end of the statement. This isknown as method chaining, and a library that supports method chaining is said to have a fluent API.Most jQuery methods return the same jQuery object on which the method was called. In theexample, I create the jQuery object by passing an HTML fragment to the $ function. This produces ajQuery object that contains an a element. The appendTo method inserts the element into the documentand returns a jQuery object that contains the same a element as its result. This allows me to make furthermethod calls, such as the one to addClass. Fluent APIs can take a while to get used to, but they enableconcise and expressive code and reduce duplication.The addClass method adds the class specified by the argument to the selected elements, like this:...Submit Order...The a.button class is defined in styles.css and brings the appearance of the a element into linewith the rest of the document.UNDERSTANDING METHOD PAIRS AND METHOD CHAININGIf you look at the methods described in Table 2-2, you will see that you can append or prepend elements intwo ways. The elements you are inserting either can be contained in the jQuery object on which you call amethod or can be in the method argument. jQuery provides different methods so you can select whichelements are contained in the jQuery object <strong>for</strong> method chaining. In my example, I used the appendTomethod, which means I can arrange things so that the jQuery object contains the element parsed from theHTML fragment, allowing me to chain the call to the addClass method and have the class applied to the aelement.The append method reverses the relationship between the parent and child elements, like this:$('#buttonDiv').append('Submit Order').addClass("button");In this statement, I select the parent element and provide the HTML fragment as the method argument.The append method returns a jQuery object that contains the buttonDiv element, so the addClass takeseffect on the parent div element rather than the new a element.23www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!