JQuery application (3) jQuery chain and jquery Application
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.
<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.
<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.
<Script type = "text/javascript"> $ (function () {$ ("div "). find ("p "). addClass ("css1 "). andSelf (). addClass ("css2") ;}); </script> <div> <p> first </p> <p> second </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:
<Div class = "css2"> <p class = "css1 css2"> section 1 </p> <p class = "css1 css2"> section 2 </p>/ div>