This article describes jQuery chain operation. Share it for your reference, as follows:
From past instances, we know that jQuery statements can be linked together, which not only shortens the code length, but also often achieves special effects.
<script type="text/javascript"> $(function() { $("div").addClass("css1").filter(function(index) { return index == 1 || $(this).attr("id") == "fourth"; }).addClass("css2"); }); </script>
The above code adds style css1 to the entire <div> list, then filters, and then adds css2 style to the filtered elements separately. If you do not use jQuery, it will be very troublesome to achieve the above effects.
In the jQuery chain, the subsequent operations are all objects with the previous operations result. If you want the operation object to be the object of 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> tag in <p>, then adds style css1, and uses the end() method to set the operation object back to $("p") and adds style css2.
In addition, the first two objects can be combined and processed together through andSelf().
Use andSelf() method to control the jQuery chain.
<script type="text/javascript"> $(function() { $("div").find("p").addClass("css1").andSelf().addClass("css2"); }); </script> <div> <p>The first paragraph</p> <p>Paragraph 2</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. Then, use the andSelf() method to combine <div> and <p>, and then adds the style css2. This style is valid for both <div> and <p>.
The operation effect is as follows:
<div class="css2"> <p class="css1 css2">The first paragraph</p> <p class="css1 css2">Paragraph 2</p> </div>
I hope this article will be helpful to everyone's jQuery programming.