jQuery-sökning - end() metod

Exempel

Välj alla paragrafer, hitta span-elementen i dessa paragrafer och återställ dem till paragrafer, samt sätt paragrafens kant till 2 pixlar röd solid.

$("p").find("span").end().css("border", "2px red solid");

Try it yourself

Definition och användning

end() metoden avslutar den närmaste filtreringen i kedjan och återställer matchande elementgruppen till dess tidigare tillstånd.

Syntax

.end()

Detaljerad förklaring

De flesta jQuery-sökmetoder manipulerar en jQuery-objektinstans och skapar en ny objekt som matchar en annan DOM-elementgrupp. När detta händer, bör den nya elementgruppen läggas till i stapeln som hålls i objektet. Varje framgångsrik filtreringssökmetod lägger till de nya elementen i stapeln. Om vi behöver den gamla elementgruppen kan vi använda end() för att poppa ut den nya sammansättningen från stapeln.

Assuming there are a pair of very short lists on the page:

<ul class="first">
   <li class="foo">list item 1</li>
   <li>list item 2</li>
   <li class="bar">list item 3</li>
</ul>
<ul class="second">
   <li class="foo">list item 1</li>
   <li>list item 2</li>
   <li class="bar">list item 3</li>
</ul>

Example 1

jQuery is particularly useful when using the chaining property (command chain). If we do not use the command chain, we usually call the previous object through variable names, so we do not need to manipulate the stack. However, through end(), we can link all method calls together:

$('ul.first').find('.foo').css('background-color', 'red')
  .end().find('.bar').css('background-color', 'green');

Try it yourself

This command chain retrieves the first list item with the class name foo and sets its background to red. end() will restore the object to the state before the find() call, so the second find() searches for '.bar' within <ul class="first">, not within the <li class="foo"> of the list, and sets the background color of the matched elements to green. The final result is that the first list items 1 and 3 have colored backgrounds set, while the items in the second list do not change at all.

Example 2

This long jQuery chain can be visualized as a structured code block, the filter method opens nested code blocks, and the end() method is used to close code blocks:

$('ul.first').find('.foo')
  .css('background-color', 'red')
.end().find('.bar')
  .css('background-color', 'green')
.end();

Try it yourself

This end() is not necessary because we will discard this jQuery object later. However, if the code is written in this form, end() can provide visual symmetry and a neat program feel, at least it is easier for developers to read, of course, the cost is that there will be a little performance loss due to additional calls.