An example analysis of jQuery chain operation

  • 2020-10-31 21:38:10
  • OfStack

This article gives an example of the jQuery chain operation. To share for your reference, the details are as follows:

From past examples, we know that the jQuery statement can be linked from 1, which not only reduces code length, but 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 is the whole < div > Add the style css1 to the list, then filter, then add the css2 style separately for the filtered elements. Without jQuery, achieving this effect would be very difficult.

In the jQuery chain, subsequent operations result in objects as a result of previous operations, and the end() method can be used if you want to operate on an object that was the object of the previous step.

end() method is used 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 is in the < p > In the search < span > Tag, then add style css1, use the end() method to set the action object back to $("p") and add style style css2.

Alternatively, the first two objects can be combined and processed together via andSelf().

jQuery chain is controlled by andSelf() method.


<script type="text/javascript">
  $(function() {
    $("div").find("p").addClass("css1").andSelf().addClass("css2");
  });
</script>
<div>
  <p> The first 1 Period of </p>
  <p> The first 2 Period of </p>
</div>

Above jQuery code first in < div > In the search < p > Tag, add css1, this style only works < p > The tag is valid, and then the andSelf() method will be used < div > and < p > Combine at 1, then add style css2, this style pair < div > and < p > Are effective.

The operation effect is as follows:


<div class="css2">
  <p class="css1 css2"> The first 1 Period of </p>
  <p class="css1 css2"> The first 2 Period of </p>
</div>

I hope this article has been helpful for jQuery programming.


Related articles: