LEARNING JAVASCRIPT - Trang 291

this behavior, call

preventDefault()

on the event object. Most of the event handlers

you write will call

preventDefault()

(unless you explicitly want to do something in

addition to the default handler).
To add our highlights, we call

highlightParas

, passing in the value of the button’s

containing

data element: this allows us to change the text we’re looking for simply by

changing the HTML!

Event Capturing and Bubbling

Because HTML is hierarchical, events can be handled in multiple places. For example,

if you click on a button, the button itself could handle the event, the button’s parent,

parent’s parent, and so on. Because multiple elements have the opportunity to handle

the event, the question becomes “in what order do elements get the opportunity to

respond to the event?”
There are essentially two options. One is to start at the most distant ancestor. This is

called capturing. In our example, our buttons are children of

<div id="content">

which is, in turn, a child of

<body>

. Therefore,

<body>

has the opportunity to “cap‐

ture” events destined for the buttons.
The other option is to start at the element where the event occurred, and then walk

up the hierarchy so all ancestors have a chance to respond. This is called bubbling.
To support both options, HTML5 event propagation starts by allowing handlers to

capture the event (starting at the most distant ancestor and working down to the tar‐

get element) and then the event bubbles back up from the target element to the most

distant ancestor.
Any handler can optionally do one of three things to affect how (and if) additional

handlers will get called. The first and most common, which we’ve already seen, is

preventDefault

, which cancels the event. Canceled events continue propagating, but

their

defaultPrevented

property is set to

true

. Event handlers built into the browser

will respect the

defaultPrevented

property and take no action. Event handlers that

you write can (and usually do) choose to ignore this property. The second approach is

to call

stopPropagation

, which prevents further propagation past the current ele‐

ment (all handlers attached to the current element will be called, but no handlers

attached to other elements). Finally—the big gun—

stopImmediatePropagation

will

prevent any further handlers from getting called (even if they’re on the current ele‐

ment).
To see all of this in action, consider the following HTML:

<!

doctype

html

>

<

html

>

<

head

>

<

title

>

Event

Propagation

<

/title>

Events | 267

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.