Вы находитесь на странице: 1из 23

1

Chapter 1: jQuery is an open source javascript library that simplifies the interaction between an HTML document or more precisely the DOC M!"T O#$!CT MOD!L%a&a DOM' and javascript( jQuery ma&es D)"*M+C HTML%DHTML' dead easy( The jQuery Philosophy: The jQuery ,hilosophy is -write less.do more/( The ,hilosophy can be further bro&en down into three concepts0 1( 1indin2 some elements % via C33 selectors' and doin2 somethin2 with them(%via jQuery methods'( 4( Chainin2 Multiple jQuery methods on a set of elements( 5( sin2 the jQuery wrapper and implicit iteration( 1. Finding some elements and doing something with them: 1or e6ample. let7s e6amine a scenario where you want to hide a 8div9 from the user. load some new te6t content into the hidden 8div9. chan2e an attribute of the selected 8div9. and then finally ma&e the hidden 8div9 visible a2ain( 8:DOCT),! html9 8html9 8head9 8script type;<te6t=$ava3cript< src;<j>uery(js<98=script9 8=head9 8body9 8div9old content8=div9 8script9 ==hide all divs on the pa2e jQuery%?div?'(hide%'@ ==update the te6t contained inside of all divs jQuery%?div?'(te6t%?new content?'@ ==add a class attribute with a value of updatedContent to all divs jQuery%?div?'(addClass%<updatedContent<'@ ==show all divs on the pa2e jQuery%?div?'(show%'@ 8=script9 8=body9 8=html9 Let7s step throu2h these four jQuery statements0 A Hide the 8div9 element on the pa2e so it7s hidden from the user7s view(

A Beplace the te6t inside the hidden 8div9 with some new te6t %new content'( A pdate the 8div9 element with a new attribute %class' and value %updatedContent'( A 3how the 8div9 element on the pa2e so it7s visible a2ain to the viewin2 user( +n our code e6ample. we found all the 8div9 elements in the HTML pa2e usin2 the jQuery function %jQuery%''. and then usin2 jQuery methods we did somethin2 with them %e(2(. hide%'. te6t%'. addClass%'. show%''( 2. Chaining: jQuery is constructed in a manner that will allow jQuery methods to be chained( 1or e6ample. why not find an element once and then chain operations onto that elementCOur former code e6ample demonstratin2 the -1ind some elements and do somethin2 with them/ concept could be rewritten to a sin2le $ava3cript statement usin2 chainin2( This code. usin2 chainin2. can be chan2ed from this0
//hide all divs on the page jQuery('div').hide(); //update the text contained inside of the div jQuery('div').text('new content'); //add a class attribute with a value of updatedContent to all divs jQuery('div').addClass("updatedContent"); //show all divs on the page jQuery('div').show();

to this:
jQuery('div').hide().text('new content').addClass("updatedContent").show();

or, with indenting and line brea s, to this:


jQuery('div') .hide() .text('new content') .addClass("updatedContent") .show();

,lainly spea&in2. chainin2 simply allows you to apply an endless chain of jQuery methods on the elements that are currently selected usin2 the jQuery function( 3. jQuery wrapper set: +n the followin2 updated code e6ample. + have added three additional 8div9 elements to the HTML pa2e. for a total of four 8div9 elements0
!"#$C%&'( ht)l '*+,-C .///01C//#%# 23%4, 567 %ransitional//(8. .http://www6w16org/%9/xht)l5/#%#/xht)l5/transitional6dtd.: !ht)l: !head: !script type;.text/<ava=cript. src;.http://ajax6googleapis6co)/ajax/libs/ j>uery/56167/j>uery6)in6js.:!/script: !/head: !body: !div:old content!/div: <div>old content</div>

<div>old content</div> <div>old content</div> !script: //hide all divs on the page jQuery('div')6hide()6text('new content')6addClass(.updatedContent.)6show()? !/script: !/body: !/ht)l:

)ou may not have e6plicitly written any pro2rammatic loops here. but 2uess whatCjQuery is 2oin2 to scan the pa2e and place all 8div9 elements in the wrapper set so thatthe jQuery methods + am usin2 here are performed %a&a implicit iteration' on each element in the set( Drappin2 your head around %pun intended' the wrapper set and its default loopin2 system %a&a implicit iteration' is critical for buildin2 advanced concepts around loopin2( $ust &eep in mind that a simple loop is occurrin2 here before you actually do any additional loopin2 %e(2(. jQuery%?div?'(each%function%'EF'( jQuery isc each() !ethod" 8:DOCT),! html9 8html9 8head9 8script src;<j>uery(js<9 8=script9 8script9 G%document'(ready%function%'E G%<button<'(clic&%function%'E G%<li<'(each%function%'E alert%G%this'(te6t%'' F'@ F'@ F'@ 8=script9 8=head9 8body9 8button9*lert the value of each list item8=button9 8ul9 8li9Coffee8=li9 8li9Mil&8=li9 8li93oda8=li9 8=ul9 8=body9 8=html9 Definition and sage:

The each%' method specifies a function to run for each matched element(

Tip: return false can be used to stop the loop early(


!ynta" G%selector'(each%function(index,element)' function(index,element) Be>uired( * function to run for each matched element(

indexI The inde6 position of the selector elementI The current element

%the <this< selector can also be used'

The G(each%' function is not the same as G%selector'(each%'. which is used to iterate. e6clusively. over a jQuery object( G%?a?'(each%function%inde6. value'E console(lo2%G%this'(attr%?href?''@ F'@ ==outputs0 every lin&s href element on your web pa2e G%?a?'(each%function%inde6. value'E var ihref ; G%this'(attr%?href?'@ if %ihref(inde6Of%<http<' 9; J' E console(lo2%ihrefK?8br=9?'@ F F'@ ==outputs0 every e6ternal href on your web pa2e

#ow the jQuery $%& is or'ani(ed"


+ su22est memoriLin2 the *,+ outline. or at the very least the topIlevel cate2ories( A jQuery Core M The jQuery 1unction M jQuery Object *ccessors M Data M ,lu2ins M +nteroperability A 3electors M #asics M Hierarchy M #asic 1ilters M Content 1ilters

M Oisibility 1ilters M *ttribute 1ilters M Child 1ilters M 1orms M 1orm 1ilters A *ttributes M *ttr M Class M HTML M Te6t M Oalue A Traversin2 M 1ilterin2 M 1indin2 M Chainin2 A Manipulation M Chan2in2 Contents M +nsertin2 +nside M +nsertin2 Outside M +nsertin2 *round M Beplacin2 M Bemovin2 M Copyin2 A C33 M C33 M ,ositionin2 M Hei2ht and Didths A !vents M ,a2e Load M !vent Handlin2 M Live !vents M +nteraction Helpers M !vent Helpers A !ffects M #asics M 3lidin2 M 1adin2 M Custom M 3ettin2s A *ja6 M *$*P Be>uests M *$*P !vents M Misc( A tilities

M #rowser and 1eature Detection M *rray and Object Operations M Test Operations M 3trin2 Operations M rls 1.2 #"e$uting jQuery%&a'a!$ript Coded (fter the D)* +as ,oaded -ut .efore Complete Page ,oad: !olution jQuery provides the ready%' method. which is a custom event handler that is typically bound to the DOM7s document object( The ready%' method is passed a sin2le parameter. a function. that contains the $ava3cript code that should be e6ecuted once the DOM is ready to be traversed and manipulated( The followin2 is a simple e6ample of this event openin2 an alert%' window once the DOM is ready but before the pa2e is completely loaded0 8:DOCT),! html9 8html9 8head9 8meta httpIe>uiv;<ContentIType< content;<te6t=html@ charset; T1IR< =9 8script type;<te6t=$ava3cript< src;<j>uery(js<98=script9 8script type;<te6t=$ava3cript<9 jQuery%document'(ready%function%' E ==DOM not loaded. must use ready event alert%jQuery%?p?'(te6t%''@ F'@ 8=script9 8=head9 8body9 8p9The DOM is ready:8=p9 8=body9 8=html9 Dis$ussion: The ready%' event handler method is jQuery7s replacement for usin2 the $ava3cript core window(onload event( +t can be used as many times as you li&e( Dhen usin2 this custom event. it7s advisable that it be included in your web pa2es after the inclusion of stylesheet declarations and includes( Doin2 this will ensure that all element properties are correctly defined before any jQuery code or $ava3cript code will be e6ecuted by the ready%' event( *dditionally. the jQuery function itself provides a shortcut for usin2 the jQuery custom ready event( sin2 this shortcut. the followin2 alert%' e6ample can be rewritten li&e so0 8:DOCT),! html 9 8html9

8head9 8meta httpIe>uiv;<ContentIType< content;<te6t=html@ charset; T1IR< =9 8script type;<te6t=$ava3cript< src;<>uery(js<98=script9


!script type;.text/<ava=cript.: jQuery()unction()* //+, alert(jQuery('p').text()); .); not loaded- !ust use ready event

8=script9 8=head9 8body9 8p9The DOM is ready:8=p9 8=body9 8=html9 The use of this custom jQuery event is necessary only if $ava3cript has to be embedded in the document flow at the top of the pa2e and encapsulated in the 8head9 element( + simply avoid the usa2e of the ready%' event by placin2 all $ava3cript includes and inline code before the closin2 8body9 element( + do this for two reasons( 1irst. modern optimiLation techni>ues have declared that pa2es load faster when the $ava3cript is loaded by the browser at the end of a pa2e parse( +n other words. if you put $ava3cript code at the bottom of a web pa2e. then the browser will load everythin2 in front of it before it loads the $ava3cript( This is a 2ood thin2 because most browsers will typically stop processin2 other loadin2 initiatives until the $ava3cript en2ine has compiled the $ava3cript contained in a web pa2e( +t7s sort of a bottlenec& in a sense that you have $ava3cript at the top of a web pa2e document( + realiLe that for some situations it7s easier to place $ava3cript in the 8head9 element( #ut honestly. +7ve never seen a situation where this is absolutely re>uired( *ny obstacle that +7ve encountered durin2 my development by placin2 $ava3cript at the bottom of the pa2e has been easily overcome and well worth the optimiLation 2ains( 3econd. if speedy web pa2es are our 2oal. why wrap more functionality around a situation that can be elevated by simply movin2 the code to the bottom of the pa2eC Dhen 2iven the choice between more code or less code. + choose less code( "ot usin2 the ready%' event results in usin2 less code. especially since less code always runs faster than more code( Dith some rationale out of the way. here is an e6ample of our alert%' code that does not use the ready%' event0 8:DOCT),! html , #L+C <I==D5C==DTD PHTML 1(J Transitional==!"< <http0==www(w5(or2=TB=6html1=DTD=6html1Itransitional(dtd<9 8html9 8head9 8meta httpIe>uiv;<ContentIType< content;<te6t=html@ charset; T1IR< =9

8=head9 8body9 8p9The DOM is ready:8=p9 8script type;<te6t=$ava3cript< src;<http0==aja6(2oo2leapis(com=aja6=libs=j>uery=1(5(4=j>uery(min(js<98=script9 8script type;<te6t=$ava3cript<9 alert/jQuery/0p01.te"t/112%%go for it the D)* is loaded 8=script9 8=body9 8=html9 "otice that + have placed all of my $ava3cript before the closin2 8=body9 element( *ny additional mar&up should be placed above the $ava3cript in the HTML document( The +T*, D)* /Do$ument )-je$t *odel1 Dhen a web pa2e is loaded. the browser creates a Document )bject *odel of the pa2e( The +T*, D)* model is constructed as a tree of )-je$ts0

jQuery ready/1 fun$tion: se ready%' to ma&e a function available after the document is loaded0 8:DOCT),! html9 8html9 8head9

8script src;<http0==aja6(2oo2leapis(com=aja6=libs=j>uery=1(1J(4=j>uery(min(js<9 8=script9 8script9 G%document'(ready%function%'E G%<button<'(clic&%function%'E G%<p<'(slideTo22le%'@ F'@ F'@ 8=script9 8=head9 8body9 8p9This is a para2raph(8=p9 8button9To22le between slide up and slide down for a p element8=button9 8=body9 8=html9 Definition0 The ready event occurs when the DOM %document object model' has been loaded( #ecause this event occurs after the document is ready. it is a 2ood place to have all other jQuery events and functions( Li&e in the e6ample above( The ready%' method specifies what happens when a ready event occurs( Tip: The ready%' method should not be used to2ether with 8body onload;<<9( !ynta": Two synta6es can be used0 G%document'(ready%function' The ready%' method can only be used on the current document. so no selector is re>uired0 G%function' function Be>uired( 3pecifies the function to run after the document is loaded

1.3 !ele$ting D)* elements sing !ele$tors and the jQuery Fun$tion: ,roblem0 )ou need to select a sin2le DOM element and=or a set of DOM elements in order to operate on the

1J

element%s' usin2 jQuery methods( 3olution0 jQuery provides two options when you need to select element%s' from the DOM( #oth options re>uire the use of the jQuery function %jQuery%' or alias G%''( The first option. which uses C33 selectors and custom selectors. is by far the most used and most elo>uent solution( #y passin2 the jQuery function a strin2 containin2 a selector e6pression. the function will traverse the DOM and locate the DOM nodes defined by the e6pression( *s an e6ample. the followin2 code will select all the 8a9 elements in the HTML document0 8:DOCT),! html , #L+C <I==D5C==DTD PHTML 1(J Transitional==!"< <http0==www(w5(or2=TB=6html1=DTD=6html1Itransitional(dtd<9 8html9 8head9 8meta httpIe>uiv;<ContentIType< content;<te6t=html@ charset; T1IR< =9 8=head9 8body9 8a href;?U?9lin&8=a9 8a href;?U?9lin&8=a9 8a href;?U?9lin&8=a9 8a href;?U?9lin&8=a9 8a href;?U?9lin&8=a9 8a href;?U?9lin&8=a9 8script type;<te6t=$ava3cript< src;<http0==aja6(2oo2leapis(com=aja6=libs=j>uery=1(5(4=j>uery(min(js<98=script9 8script type;<te6t=$ava3cript<9 ==alerts there are Q elements alert%?,a2e contains ? K jQuery/0a01(len2th K ? 8a9 elements:?'@ 8=script9 8=body9 8=html9 +f you were to run this HTML pa2e in a web browser. you would see that the code e6ecutes a browser alert%' that informs us that the pa2e contains si6 8a9 elements( + passed this value to the alert%' method by first selectin2 all the 8a9 elements and then usin2 the len2th property to return the number of elements in the jQuery wrapper set( )ou should be aware that the first parameter of the jQuery function. as we are usin2 it here. will also accept multiple e6pressions( To do this. simply separate multiple selectors with a comma inside the same strin2 that is passed as the first parameter to the jQuery function( Here is an e6ample of what that mi2ht loo& li&e0 jQuery%?selector1. selector4. selector5?'(len2th@ Our second option for selectin2 DOM elements and the less common option is to pass

11

the jQuery function an actual $ava3cript reference to DOM element%s'( *s an e6ample. the followin2 code will select all the 8a9 elements in the HTML document( "otice that +7m passin2 the jQuery function an array of 8a9 elements collected usin2 the 2et!lements#yTa2"ame DOM method( This e6ample produces the same e6act results as our previous code e6ample0 8:DOCT),! html , #L+C <I==D5C==DTD PHTML 1(J Transitional==!"< <http0==www(w5(or2=TB=6html1=DTD=6html1Itransitional(dtd<9 8html9 8head9 8meta httpIe>uiv;<ContentIType< content;<te6t=html@ charset; T1IR< =9 8=head9 8body b2color;<yellow<9 8:II yes the attribute is depreciated. + &now. roll with it II9 8a href;?U?9lin&8=a9 8a href;?U?9lin&8=a9 8a href;?U?9lin&8=a9 8a href;?U?9lin&8=a9 8a href;?U?9lin&8=a9 8a href;?U?9lin&8=a9 8script type;<te6t=$ava3cript< src;<http0==aja6(2oo2leapis(com=aja6=libs=j>uery=1(5(4=j>uery(min(js<98=script9 8script type;<te6t=$ava3cript<9 ==alerts there are Q elements alert%?,a2e contains ? K jQuery/do$ument.get#lements.yTag3ame/0a011(len2th K ? 8a9 !lements. *nd has a ? K jQuery%document(body'(attr%?b2color?' K ? bac&2round?'@ 8=script9 8=body9 8=html9 1.4 !ele$ting D)* elements within a spe$ified $onte"t: 3olution The jQuery function when passed a C33 e6pression will also accept a second parameter that tells the jQuery function to which conte6t it should search for the DOM elements based on the e6pression( The second parameter in this case can be a DOM reference. jQuery wrapper. or document( +n the followin2 code. there are 14 8input9 elements( "otice how + use a specific conte6t. based on the 8form9 element. to select only particular 8input9 elements0
!"#$C%&'( ht)l '*+,-C .///01C//#%# 23%4, 567 %ransitional//(8. .http://www6w16org/%9/xht)l5/#%#/xht)l5/transitional6dtd.: !ht)l: !head: !)eta http/e>uiv;.Content/%ype. content;.text/ht)l? charset;*%@/A. /: !/head:

14

!body: !for): !input na)e;.. type;.chec box. /: !input na)e;.. type;.radio. /: !input na)e;.. type;.text. /: !input na)e;.. type;.button. /: !/for): !for): !input na)e;.. type;.chec box. /: !input na)e;.. type;.radio. /: !input na)e;.. type;.text. /: !input na)e;.. type;.button. /: !/for): !input na)e;.. type;.chec box. /: !input na)e;.. type;.radio. /: !input na)e;.. type;.text. /: !input na)e;.. type;.button. /: !script type;.text/<ava=cript. src;.http://ajax6googleapis6co)/ajax/libs/j>uery/5616B/j>uery6)in6js.:!/script: !script type;.text/<ava=cript.: //searches within all for) ele)ents, using a wrapper for context, alerts .A inputs. alert('selected ' C jQuery('input',/(')or!'))6length C ' inputs')? //search with the first for) ele)ent, using #$4 reference as the context, alerts //.D inputs. alert('selected' C jQuery('input',docu!ent.)or!s012)6length C ' inputs')? //search within the body ele)ent for all input ele)ents using an expression, //alerts .5B inputs. alert('selected' C jQuery('input','3ody')6length C ' inputs')? !/script: !/body: !/ht)l:

1.5 Filtering a wrapper set of D)* elements: Pro-lem: )ou have a set of selected DOM elements in a jQuery wrapper set but want to remove DOM elements from the set that do not match a new specified e6pression%s' in order to create a new set of elements to operate on( !olution: The jQuery filter method. used on a jQuery wrapper set of DOM elements. can e6clude elements that do not match a specified e6pression%s'( +n short. the filter%' method allows you to filter the current set of elements( This is an important distinction from the jQuery find method. which will reduce a wrapped set of DOM elements by findin2 %via a new selector e6pression' new elements. includin2 child elements of the current wrapped set(

15

To understand the filter method. let7s e6amine the followin2 code0 8:DOCT),! html , #L+C <I==D5C==DTD PHTML 1(J Transitional==!"< <http0==www(w5(or2=TB=6html1=DTD=6html1Itransitional(dtd<9 8html9 8head9 8meta httpIe>uiv;<ContentIType< content;<te6t=html@ charset; T1IR< =9 8=head9 8body9 8a href;<U< class;<e6ternal<9lin&8=a9 8a href;<U< class;<e6ternal<9lin&8=a9 8a href;<U<98=a9 8a href;<U< class;<e6ternal<9lin&8=a9 8a href;<U< class;<e6ternal<9lin&8=a9 8a href;<U<98=a98=li9 8a href;<U<9lin&8=a9 8a href;<U<9lin&8=a9 8a href;<U<9lin&8=a9 8a href;<U<9lin&8=a9 8script type;<te6t=$ava3cript< src;<http0==aja6(2oo2leapis(com=aja6=libs=j>uery=1(5(4=j>uery(min(js<98=script9 8script type;<te6t=$ava3cript<9 ==alerts H left in the set alert%jQuery%?a?'.filter/0.e"ternal01(len2th K ? e6ternal lin&s?'@ 8=script9 8=body9 8=html9 The HTML pa2e in the code e6ample just shown contains a web pa2e with 1J 8a9 elements( Those lin&s that are e6ternal lin&s are 2iven a class name of e6ternal( sin2 the jQuery function. we select all 8a9 elements on the pa2e( Then. usin2 the filter method. all those elements that do not have a class attribute value of e6ternal are removed from the ori2inal set( Once the initial set of DOM elements are altered usin2 the filter%' method. + invo&e the len2th property. which will tell me how many elements are now in my new set after the filter has been applied( Dis$ussion +t7s also possible to send the filter%' method a function that can be used to filter the wrapped set( Our previous code e6ample. which passes the filter%' method a strin2 e6pression. can be chan2ed to use a function instead0 alert% jQuery%?a?' (filter%fun$tion/inde"16 return 7/this1.hasClass/0e"ternal0128' (len2th K ? e6ternal lin&s? '@ "otice that + am now passin2 the filter%' method an anonymous function( This function

1H

is called with a conte6t e>ual to the current element( That means when + use G%this' within the function. + am actually referrin2 to each DOM element in the wrapper set( Dithin the function. + am chec&in2 each 8a9 element in the wrapper set to see whether the element has a class value %hasClass%'' of e6ternal( +f it does. #oolean true. then &eep the element in the set. and if it doesn7t %false'. then remove the element from the set( *nother way to loo& at this is if the function returns false. then the element is removed( +f the function returns any other data value besides false. then the element will remain in the wrapper set( )ou may have noticed that + have passed the function a parameter named inde6 that + am not usin2( This parameter. if needed. can be used to refer numerically to the inde6 of the element in the jQuery wrapper set( 1.9 Finding Des$endant #lements :ithin the Currently !ele$ted :rapper !et Pro-lem )ou have a set of selected DOM elements %or a sin2le element' and want to find descendant %children' elements within the conte6t of the currently selected elements( !olution se the (find%' method to create a new wrapper set of elements based on the conte6t of the current set and their descendants( 1or e6ample. say that you have a web pa2e that contains several para2raphs( !ncapsulated inside of these para2raphs are words that are emphasiLed %italic'( +f you7d li&e to select only 8em9 elements contained within 8p9 elements. you could do so li&e this0 8:DOCT),! html , #L+C <I==D5C==DTD PHTML 1(J Transitional==!"< <http0==www(w5(or2=TB=6html1=DTD=6html1Itransitional(dtd<9 8html9 8head9 8meta httpIe>uiv;<ContentIType< content;<te6t=html@ charset; T1IR< =9 8=head9 8body9 8p9 t ad videntur facilisis 8em9elit8=em9 cum( "ibh insitam erat facit 8em9saepius8=em9 ma2na( "am e6 liber iriure et imperdiet( !t mirum eros iis te habent( 8=p9 8p9Claram claritatem eu amet di2nissim ma2na( Di2nissim >uam elit facer eros illum( !t >ui e6 esse 8em9tincidunt8=em9 anteposuerit( "ulla nam odio ii vulputate feu2ait(8=p9 8p9+n >uis 8em9laoreet8=em9 te le2unt euismod( Claritatem 8em9consuetudium8=em9 wisi sit velit facilisi(8=p9 8script type;<te6t=$ava3cript< src;<http0==aja6(2oo2leapis(com=aja6=libs=j>uery=1(5(4=j>uery(min(js<98=script9 8script type;<te6t=$ava3cript<9 ==alerts total italic words found inside of 8p9 elements alert%?The three para2raphs in all contain ? K jQuery%?p?'(find/0em01(len2th K ? italic words?'@

1N

8=script9 8=body9 8=html9 Veep in mind that we could have also written this code by passin2 a conte6tual reference as a second parameter to the jQuery function0 alert%?The three para2raphs in all contain ? K jQuery/0em0;7/0p011(len2th K? italic words?'@ *dditionally. it7s worth mentionin2 that the last two code e6amples are demonstrative in purpose( +t is li&ely more lo2ical. if not pra2matic. to use a C33 selector e6pression to select all the descendant italic elements contained within the ancestor 8p9 elements( alert%?The three para2raphs in all contain ? K jQuery/0p em01(len2th K italic words?'@ Dis$ussion: The jQuery (find%' method can be used to create a new set of elements based on conte6t of the current set of DOM elements and their children elements( ,eople often confuse the use of the (filter%' method and (find%' method( The easiest way to remember the difference is to &eep in mind that (find%' will operate=select the children of the current set while (filter%' will only operate on the current set of elements( +n other words. if you want to chan2e the current wrapper set by usin2 it as a conte6t to further select the children of the elements selected. use (find%'( +f you only want to filter the current wrapped set and 2et a new subset of the current DOM elements in the set only. use (filter%'( To boil this down even more. find%' returns children elements. while filter%' only filters what is in the current wrapper set( 1.< =eturning to the Prior !ele$tion .efore a Destru$ti'e Change ,roblem * destructive jQuery method %e(2(. filter%' or find%'' that was used on a set of elements needs to be removed so that the set prior to the use of the destructive method is returned to its previous state and can then be operated as if the destructive method had never been invo&ed( jQuery end%' method0 Des$ription: The end/ 1 method reverts the most recent destru$ti'e operation. chan2in2 the set of matched elements to its previous state ri2ht before the destructive operation( !ynta": operations(end% '

#"ample:

1Q

1ollowin2 is a simple e6ample a simple showin2 the usa2e of this method( This selects all para2raphs. finds span elements inside these. and reverts the selection bac& to the para2raphs( 8html9 8head9 8title9the title8=title9 8script type;<te6t=javascript< src;<=j>uery=j>ueryI1(5(4(min(js<98=script9 8script9 G%document'(ready%function%'E G%<p<'(find%<span<'(end%'(css%<border<. <4p6 red solid<'@ F'@ 8=script9 8style9 pE mar2in01Jp6@ paddin201Jp6@ F 8=style9 8=head9 8body9 8p98span9Hello8=span9. how are youC8=p9 8=body9 8=html9 !olution: jQuery provides the end%' method so that you can return to the previous set of DOM elements that were selected before usin2 a destructive method( To understand the end%' method. let7s e6amine the followin2 HTML( 8:DOCT),! html , #L+C <I==D5C==DTD PHTML 1(J Transitional==!"< <http0==www(w5(or2=TB=6html1=DTD=6html1Itransitional(dtd<9 8html9 8head9 8meta httpIe>uiv;<ContentIType< content;<te6t=html@ charset; T1IR< =9 8=head9 8body9 8p9te6t8=p9 8p class;<middle<9Middle 8span9te6t8=span98=p9 8p9te6t8=p9 8script type;<te6t=$ava3cript< src;<http0==aja6(2oo2leapis(com=aja6=libs=j>uery=1(5(4=j>uery(min(js<98=script9 8script type;<te6t=$ava3cript<9 alert%jQuery%?p?'(filter%?(middle?'(len2th'@ ==alerts 1 alert%jQuery%?p?'(filter%?(middle?'(end/1(len2th'@ ==alerts 5

1S

alert%jQuery%?p?'(filter%?(middle?'(find%?span?'.end/1.end/1(len2th'@ ==alerts 5 8=script9 8=body9 8=html9 The first alert%' statement in the code contains a jQuery statement that will search the document for all 8p9 elements and then apply filter%' to the selected 8p9 elements in the set selectin2 only the one%s' with a class of middle( The len2th property then reports how many elements are left in the set0 alert%jQuery%?p?'(filter%?(middle?'(len2th'@ ==alerts 1 The ne6t alert%' statement ma&es use of the end%' method( Here we are doin2 everythin2 we did in the prior statement e6cept that we are undoin2 the filter%' method and returnin2 to the set of elements contained in the wrapper set before the filter%' method was applied0 alert%jQuery%?p?'(filter%?(middle?'(end/1(len2th'@ ==alerts 5 The last alert%' statement demonstrates how the end%' method is used twice to remove both the filter%' and find%' destructive chan2es. returnin2 the wrapper set to its ori2inal composition0 alert%jQuery%?p?'(filter%?(middle?'(find%?span?'.end/1.end/1(len2th'@ ==alerts 5 Discussion0 +f the end%' method is used and there were no prior destructive operations performed. an empty set is returned( * destructive operation is any operation that chan2es the set of matched jQuery elements. which means any traversin2 or manipulation method that returns a jQuery object. includin2 add%'. and3elf%'. children%'. closes%'. filter%'. find%'. map%'. ne6t%'. ne6t*ll%'. not%'. parent%'. parents%'. prev%'. prev*ll%'. siblin2s%'. slice%'. clone%'. appendTo%'. prependTo%'. insert#efore%'. insert*fter%'. and replace*ll%'( 1.> ?n$luding the Pre'ious !ele$tion with the Current !ele$tion ,roblem )ou have just manipulated a set of elements in order to ac>uire a new set of elements( However. you want to operate on the prior set as well as the current set( 3olution )ou can combine a prior selection of DOM elements with the current selection by usin2 the and3elf%' method( 1or e6ample. in the followin2 code. we are first selectin2 all 8div9 elements on the pa2e( "e6t we manipulate this set of elements by findin2 all 8p9 elements contained within the 8div9 elements( "ow. in order to operate on both the 8div9 and the 8p9 elements found within the 8div9. we could include the 8div9 into the current set by usin2 and3elf%'( Had + omitted the and3elf%'. the border color would have only been applied to the 8p9 elements0 8:DOCT),! html , #L+C <I==D5C==DTD PHTML 1(J Transitional==!"<

1R

<http0==www(w5(or2=TB=6html1=DTD=6html1Itransitional(dtd<9 8html9 8head9 8meta httpIe>uiv;<ContentIType< content;<te6t=html@ charset; T1IR< =9 8=head9 8body9 @di'A @pAParagraph@%pA @pAParagraph@%pA @%di'A 8script type;<te6t=$ava3cript< src;<http0==aja6(2oo2leapis(com= aja6=libs=j>uery=1(5(4=j>uery(min(js<98=script9 8script type;<te6t=$ava3cript<9 jQuery/0di'01.find/0p01.and!elf/1.$ss/0-order0;01p" solid BCC33DD012 8=script9 8=body9 8=html9 Discussion Veep in mind that when you use the and3elf%' method. it will only add into the current set bein2 operated on and the prior set. but not all prior sets( 1.C Tra'ersing the D)* .ased on Eour Current Conte"t to ($Fuire a 3ew !et of D)* #lements ,roblem )ou have selected a set of DOM elements. and based on the position of the selections within the DOM tree structure. you want to traverse the DOM to ac>uire a new set of elements to operate on( 3olution jQuery provides a set of methods for traversin2 the DOM based on the conte6t of the currently selected DOM element%s'( 1or e6ample. let7s e6amine the followin2 HTML snippet0 8div9 8ul9 8li98a href;<U<9lin&8=a98=li9 @liA@a hrefGHBHAlinI@%aA@%liA 8li98a href;<U<9lin&8=a98=li9 8li98a href;<U<9lin&8=a98=li9 8=ul9 8=div9 "ow. let7s select the second 8li9 element usin2 the 0e>%' inde6 custom selector0 ==selects the second element in the set of 8li9?s by inde6. inde6 starts at J jQuery%?li:eF/1'?'@

1T

De now have a conte6t. a startin2 point within the HTML structure( Our startin2 point is the second 8li9 element( 1rom here we can 2o anywhereMwell. almost anywhere( Let7s see where we can 2o usin2 a couple of the methods jQuery provides for traversin2 the DOM( Bead the comments in the code for clarification0 jQuery%?li0e>%1'?'.ne"t/' ==selects the third 8li9 jQuery%?li0e>%1'?'.pre'/1 ==selects the first 8li9 jQuery%?li0e>%1'?'.parent/1 ==selects the 8ul9 jQuery%?li0e>%1'?'.parent/1.$hildren/1 ==selects all 8li9s jQuery%?li0e>%1'?'.ne"t(ll/1 ==selects all the 8li9s after the second 8li9 jQuery%?li0e>%1'?'.pre'(ll/1 ==selects all the 8li9s before the second 8li9 Veep in mind that these traversin2 methods produce a new wrapper set. and to return to the previous wrapper set. you can use end%'( Discussion0 The traversin2 methods shown thus far have demonstrated simple traverses( There are two additional concepts that are important to &now about traversin2( The first concept and li&ely most obvious is that traversin2 methods can be chained( Let7s e6amine a2ain the followin2 jQuery statement from earlier0 jQuery%?li0e>%1'?'.parent/1.$hildren/1 ==selects all 8li9?s "otice that + have traversed from the second 8li9 element to the parent 8ul9 element and then a2ain traversed from the parent element to selectin2 all the children elements of the 8ul9 element( The jQuery wrapper set will now contain all the 8li9 elements contained within the 8ul9( Of course. this is a contrived e6ample for the purpose of demonstratin2 traversin2 methods( Had we really wanted a wrapper set of just 8li9 elements. it would have been much simpler to select all the 8li9 elements from the 2etI2o %e(2(. jQuery%?li?''( The second concept that you need to &eep in mind when dealin2 with the traversin2 methods is that many of the methods will accept an optional parameter that can be used to filter the selections( Let7s ta&e our chained e6ample a2ain and loo& at how we could chan2e it so that only the last 8li9 element was selected( Veep in mind that this is a contrived e6ample for the purpose of demonstratin2 how a traversin2 method can be passed an e6pression used for selectin2 a very specific element0 jQuery%?li0e>%1'?'(parent%'(children%?:last?' ==selects the last 8li9 1.1D Creating; )perating on; and ?nserting D)* #lements Pro-lem: )ou want to create new DOM elements %or a sin2le element' that are immediately selected. operated on. and then injected into the DOM( !olution: +f you provide the function with a te6t strin2 of raw HTML. it will create these elements for you on the fly( 1or e6ample. the followin2 statement will create an 8a9

4J

element wrapped inside of a 8p9 element with a te6t node encapsulated inside of the 8p9 and 8a9 elements0 jQuery%?8p98a9jQuery8=a98=p9?'@ "ow. with an element created. you can use jQuery methods to further operate on the elements you just created( +t7s as if you had selected the 8p9 element from the 2etI2o in an e6istin2 HTML document( 1or e6ample. we could operate on the 8a9 by usin2 the (find%' method to select the 8a9 element and then set one of its attributes( +n the case of the followin2 code. we are settin2 the href attribute with a value of http0== www(j>uery(com0 jQuery%?8p98a9jQuery8=a98=p9?'.find/0a01.attr/0href0;0http:%%www.jFuery.$om012 This is 2reat. ri2htC Dell. it7s about to 2et better because all we have done so far is create elements on the fly and manipulate those elements in code( De have yet to actually chan2e the currently loaded DOM. so to spea&( To do this. we7ll have to use the manipulation methods provided by jQuery( The followin2 is our code in the conte6t of an HTML document( Here we are creatin2 elements. operatin2 on those elements. and then insertin2 those elements into the DOM usin2 the appendTo%' manipulation method0 8:DOCT),! html , #L+C <I==D5C==DTD PHTML 1(J Transitional==!"< <http0==www(w5(or2=TB=6html1=DTD=6html1Itransitional(dtd<9 8html9 8head9 8meta httpIe>uiv;<ContentIType< content;<te6t=html@ charset; T1IR< =9 8=head9 8body9 8script type;<te6t=$ava3cript< src;<http0==aja6(2oo2leapis(com=aja6=libs=j>uery=1(5(4=j>uery(min(js<98=script9 8script type;<te6t=$ava3cript<9 jQuery/0@pA@aAjQuery@%aA@%pA01.find/0a01.attr/0href0;0http:%%www.jFuery.$om01 .end/1.appendTo/0-ody012 8=script9 8=body9 8=html9 "otice how + am usin2 the end%' method here to undo the find%' method so that when + call the appendTo%' method. it appends what was ori2inally contained in the initial wrapper set( Dis$ussion: +n this recipe we7ve passed the jQuery function a strin2 of raw HTML that is ta&en and used to create DOM elements on the fly( +t7s also possible to simply pass the jQuery function a DOM object created by the DOM method create!lement%'0

41

jQuery%do$ument.$reate#lement/0p01'(appendTo%?body?'@ ==adds an empty p element to the pa2e Of course. this could be rather laborious dependin2 upon the specifics of the usa2e when a strin2 of HTML containin2 multiple elements will wor& just fine( +t7s also worth mentionin2 here that we7ve only scratched the surface of the manipulation methods by usin2 the appendTo%' method( +n addition to the appendTo%' method. there are also the followin2 manipulation methods0 A append%' A prepend%' A prependTo%' A after%' A before%' A insert*fter%' A insert#efore%' A wrap%' A wrap*ll%' A wrap+nner%' 1.11 =emo'ing D)* #lements Pro-lem0 )ou want to remove elements from the DOM( !olution: The remove%' method can be used to remove a selected set of elements and their children elements from the DOM( !6amine the followin2 code0 8:DOCT),! html , #L+C <I==D5C==DTD PHTML 1(J Transitional==!"< <http0==www(w5(or2=TB=6html1=DTD=6html1Itransitional(dtd<9 8html9 8head9 8meta httpIe>uiv;<ContentIType< content;<te6t=html@ charset; T1IR< =9 8=head9 8body9 8h59*nchors8=h59 8a href;?U?9*nchor !lement8=a9 8a href;?U?9*nchor !lement8=a9 8a href;?U?9*nchor !lement8=a9 8script type;<te6t=$ava3cript< src;<http0==aja6(2oo2leapis(com=aja6=libs=j>uery=1(5(4=j>uery(min(js<98=script9 8script type;<te6t=$ava3cript<9 jQuery/0a01.remo'e/12 8=script9 8=body9 8=html9

44

Dhen the precedin2 code is loaded into a browser. the anchor elements will remain in the pa2e until the $ava3cript is e6ecuted( Once the remove%' method is used to remove all anchor elements from the DOM. the pa2e will visually contain only an 8h59 element( +t7s also possible to pass the method an e6pression to filter the set of elements to be removed( 1or e6ample. our code could chan2e to remove only anchors with a specific class0 8:DOCT),! html , #L+C <I==D5C==DTD PHTML 1(J Transitional==!"< <http0==www(w5(or2=TB=6html1=DTD=6html1Itransitional(dtd<9 8html9 8head9 8meta httpIe>uiv;<ContentIType< content;<te6t=html@ charset; T1IR< =9 8=head9 8body9 8h59*nchors8=h59 8a href;?U? class;?remove?9*nchor !lement8=a9 8a href;?U?9*nchor !lement8=a9 8a href;?U? class;<remove<9*nchor !lement8=a9 8script type;<te6t=$ava3cript< src;<http0==aja6(2oo2leapis(com=aja6=libs=j>uery=1(5(4=j>uery(min(js<98=script9 8script type;<te6t=$ava3cript<9 jQuery/0a01.remo'e/0.remo'e012 8=script9 8=body9 8=html9 Dis$ussion Dhen usin2 the jQuery remove%' method. you need to &eep two thin2s in mind0 A Dhile the elements selected are removed from the DOM usin2 remove%'. they have not been removed from the jQuery wrapper set( That means in theory you could continue operatin2 on them and even add them bac& into the DOM if desired( A This method will not only remove the elements from the DOM. but it will also remove all event handlers and internally cached data that the elements removed mi2ht have contained(

45

Вам также может понравиться