JQuery chain User Guide and jquery User Guide
In the previous example, the jQuery statement can be linked together, which not only shortens the code length, but also achieves special effects in many cases.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
$ (Function (){
$ ("Div"). addClass ("css1"). filter (function (index ){
Return index = 1 | $ (this). attr ("id") = "fourth ";
}). AddClass ("css2 ");
});
</Script>
The code above adds the style css1 to the <div> list and then filters it. Then, it adds the css2 style to the filtered elements separately. If jQuery is not used, it will be very troublesome to implement the above results.
In the jQuery chain, the subsequent operations are the objects of the previous operations. If you want the operation object to be the object in the previous step, you can use the end () method.
Use the end () method to control the jQuery chain.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
$ (Function (){
$ ("P"). find ("span"). addClass ("css1"). end (). addClass ("css2 ");
});
</Script>
<P> Hello, <span> how </span> are you? </P>
<Span> very nice, </span> Thank you.
The above code searches for the <span> flag in <p>, then adds the style css1, uses the end () method to set the operation object back to $ ("p"), and adds the style css2.
In addition, you can combine the first two objects through andSelf () and then process them together.
Use the andSelf () method to control the jQuery chain.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
$ (Function (){
$ ("Div"). find ("p"). addClass ("css1"). andSelf (). addClass ("css2 ");
});
</Script>
<Div>
<P> first paragraph </p>
<P> second paragraph </p>
</Div>
The above jQuery code first searches for the <p> tag in <div> and adds css1. This style is only valid for the <p> tag, and then uses andSelf () the method combines <div> and <p>, and then adds the style css2, which is effective for <div> and <p>.
Effect:
Copy codeThe Code is as follows:
<Div class = "css2">
<P class = "css1 css2"> first paragraph </p>
<P class = "css1 css2"> section 2 </p>
</Div>