jQuery in Action

90
CHAPTER 4
Events are where it happens!
Now let's look at even more interesting changes.
In the ready handler for the page, we use jQuery to select all elements on the
page and to iterate over each one with the
each()
method
b
. For each matched
element, we record its instance in the local variable
current
and establish an
onclick
handler
c
. This handler first employs the browser-dependent tricks that
we discussed in the previous section to locate the
Event
instance and identify the
event target, and then emits a console message. This message is the most inter-
esting part of this example.
It displays the tag name and
id
of the current element, putting closures to work
(please read section A.2.4 in appendix A if closures are a subject that gives you
heartburn), followed by the
id
of the target. By doing so, each message that's
logged to the console displays the information about the current element of the
bubble process, as well as the target element that started the whole shebang.
Loading the page (located in the file chapter4/dom.0.propagation.html) and
clicking the image result in the display of figure 4.2.
This clearly illustrates that, when the event is fired, it's delivered first to the
target element and then to each of its ancestors in turn, all the way up to the
<html>
element itself.
This is a powerful ability because it allows us to establish handlers on elements
at any level to handle events occurring on its descendents. Consider a handler on
a
<form>
element that reacts to any change event on its child elements to effect
dynamic changes to the display based upon the elements' new values.
But what if we don't want the event to propagate? Can we stop it?
Figure 4.2 The console messages clearly show the propagation of the event as it
bubbles up the DOM tree from the target element to the tree root.


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

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