jQuery in Action

46
CHAPTER 2
Creating the wrapped element set
detail in chapter 3) generates a new wrapped set, which creates copies of the ele-
ments in the first set. If, once a new wrapped set is generated, we had no way to
reference the original set, our ability to construct versatile jQuery command
chains would be curtailed.
Consider the following statement:
$('img').clone().appendTo('#somewhere');
Two wrapped sets are generated within this statement: the original wrapped set
of all the
<img>
elements on a page and a second wrapped set consisting of copies
of those elements. The
clone()
method returns this second set as its result, and
it's that set that's operated on by the
appendTo()
command.
But what if we subsequently want to apply a command, such as adding a class
name, to the original wrapped set after it's been cloned? We can't tack it onto the
end of the existing chain; that would affect the clones, not the original wrapped
set of images.
jQuery provides for this need with the
end()
command. This method, when
used within a jQuery chain, will back up to a previous wrapped set and return it as
its value so that subsequent operations will apply to the previous set.
Consider
$('img').clone().appendTo('#somewhere').end().addClass('beenCloned');
The
appendTo()
method returns the set of new clones, but by calling
end()
we
back up to the previous wrapped set (the original images), which gets operated on
by the
addClass()
command. Without the intervening
end()
command,
addClass()
would have operated on the set of clones.
It might help to think of the wrapped sets generated during a jQuery command
chain as being held on a stack. When
end()
is called, the topmost (most recent)
Command syntax: end
end()
Used within a chain of jQuery command to back up the wrapped set to a previously
returned set
Parameters
none
Returns
The previous wrapped set


Другие страницы

 
Cкачать книги бесплатно без регистрации в электронном виде (pdf, chm, txt).Вы можете читать книги онлайн на нашем сайте литературного портала книг.Большая подборка учебников, пособий, интересных книг.Электронные книги на английском языке скачать бесплатно без смс.