Chapter 7 JavaScript and HTML Documents

©

Chapter 7 JavaScript and
HTML Documents
• The chapter begins with a description of the execution
environment of cent-side JavaScript, which means the
object hierarchy that corresponds to the structure of
documents.
• We then give a brief overview of the Document Object
Model, noting that you need not know the details of this
model to be able to use cent-side JavaScript.
• The fundamental concepts of events and event handng
are then introduced. Although the event-driven model of
computation is not a new idea in programming, it is
quickly becoming more important to programmers. Next,
we describe the relationships between event objects,
HTML tag attributes, and tags, primarily by means of two
tables.

©

Chapter 7 JavaScript and
HTML Documents
• Appcations of event handng are introduced through
four examples.
– The first of these illustrates the use of the load and unload
events.
– The next example shows the use of the cck event when it is
created with radio buttons.
– The last two event-handng examples demonstrate the use of
the change and submit events to check the format of text input
through a form.
• Next, we discuss the use of the navigator object to
determine the browser being used. Finally, we present a
short discussion of the event propagation approach
recommended by the W3C, which is now supported by
the latest Netscape (6.0) and Microsoft (5.5) browsers.

©

Chapter 7 JavaScript and
HTML Documents
• 7.1 The JavaScript Execution Environment
• 7.2 The Document Object Model
• 7.3 Introduction to Events and Event Handng
• 7.4 Events, Attributes, and Tags
• 7.5 Using the load and unload Events
• 7.6 Event Handlers for Button Events
• 7.7 Checking Form Input
• 7.8 The navigator Object
• 7.9 Event Propagation
• 7.10 Summary
• 7.11 Review Questions
7.12 Exercises

©

7.1 The JavaScript Execution
Environment
• A browser displays an HTML document in
a window on the screen of the cent.
• The JavaScript Window object represents
the window that displays the document.
• The Window object provides the largest
enclosing referencing environment for
JavaScript scripts.

©

7.1 The JavaScript Execution
Environment
• All JavaScript variables are properties of
some object. The properties of the
Window object are visible to all JavaScript
scripts that appear in the Window's HTML
document. These properties include all of
the global variables (unless, of course,
they are hidden by variables with the same
names defined in some smaller scope). So,
when a global variable is impcitly created
in a cent-side script, it becomes a new
property of the Window object.

©

7.1 The JavaScript Execution
Environment
• There can be more than one Window
object. Each such object creates a global
scope and is the parent object of all
objects in the window.
• A variable declared in one Window object
is not a global variable in another Window
object, although it is possible to reference
it in the other object.
• The Window object is the ancestor of all
objects in cent-side JavaScript.

©

7.1 The JavaScript Execution
Environment
• The JavaScript Document object
represents the displayed HTML document.
Every Window object has a property
named document, which is a reference to
the Document object that the window
displays.

©

7.1 The JavaScript Execution
Environment
• Every Document object has a forms array, each element
of which represents a form in the document.
• Each Form object has an elements array as a property,
which contains the objects that represent the HTML form
elements, such as buttons and menus.
• Form elements can be addressed in a script in several
ways.
– In most cases, both forms and elements are named and the
names are used to identify them.
– However, in the case of radio buttons, this is a problem because
all radio buttons in a collection must have the same name.
Because of this, individual radio buttons are often identified as
elements of the elements array of the form in which they appear.
The examples in Section 7.6, "Event Handlers for Button
Events," illustrate the addressing of radio button elements.

©

7.1 The JavaScript Execution
Environment
• Document objects also have property
arrays for
– anchors,
– nks,
– images,
– and applets.
• There are many other objects in the object
hierarchy below a Window object, but in
this chapter we are primarily interested in
documents, forms, and elements.

©

7.2 The Document Object
Model
• The Document Object Model ( DOM) has been
under development since the mid-1990s by the
W3C. At the time of this writing, DOM Level 2
(usually referred to as DOM 2), was the latest
approved version, and DOM 3 was under
development. The original motivation for DOM
was to provide a specification that would make
Java programs and JavaScript scripts that deal
with HTML documents portable among various
browsers. DOM is a successor to Dynamic
HTML (DHTML), which was centered on
browsers. However, vendors for HTML became
involved and have influenced the form and
direction of DOM.

©

7.2 The Document Object
Model
• DOM 1 was focused on the HTML and XML
document model (see Chapter 10, "Introduction
to XML"). DOM 2 specifies a style sheet object
model and how style information attached to a
document can be manipulated. It also includes
document traversals and an event model. DOM
3 will deal with content models for XML ( DTDs
and schemas), document vadation, and
document views and formatting, as well as key
events and event groups. DOM 2 is supported
by IE5 and NN6, but not NN4.

©

7.2 The Document Object
Model
• DOM is nothing more than a model that
defines the interface between HTML and
appcation programs. It is an abstract
model because it must apply to a variety of
appcation programming languages. With
DOM, users can write code in
programming languages to create
documents, move around in their
structures, and change, add, or delete
elements and their content.

©

7.2 The Document Object
Model
• Documents in DOM have a tree-ke structure,
but there can be more than one tree in a
document. Because DOM is an abstract
interface, it does not dictate that documents
should be implemented as trees or collections of
trees. Therefore, in an implementation, the
relationships among the elements of a document
can be represented in any number of different
ways. DOM is not a data model; it is an objectoriented
model. Therefore, the elements of a
document using the DOM model are objects,
with both data and operations.

©

7.2 The Document Object
Model
• The following HTML table and its corresponding
DOM tree illustrate the relationship between them.
<table>
<
tr
>
<
th
> Breakfast </
th
>
<td> 0 </td>
<td> 1 </td>
</
tr
>
<
tr
>
<
th
> Lunch </
th
>
<td> 1 </td>
<td> 0 </td>
</
tr
>
</table>
<table>
<tr> <tr>
<th> <td> <td> <th> <td> <td>
breakfast 0 1 Lunch 1 0

©

7.2 The Document Object
Model
• object with two properties, type and name,
with the values "text" and " address ",
respectively:
<input type = "text" name = "address">
• In most cases, the property names in
JavaScript are lowercase versions of their
corresponding attribute names in HTML.

©

7.3 Introduction to Events and
Event Handng
• One important category of use of JavaScript for
Web programming is to detect certain activities
of the browser and the browser user, and
provide computation when these activities occur.
This is specified using a special form of
program-ming called event-driven programming.
– In conventional (non-event-driven) programming, the
programmer writes code, and the code itself specifies
the order in which that code is executed, although the
order is usually affected by the program's input data.
– In event-driven programming, parts of the program
are executed at completely unpredictable times, often
triggered indirectly by user interactions with the
executing program.

©

7.3 Introduction to Events and
Event Handng
• An event is a notification that something
specific has occurred, either with the
browser, such as
– the completion of the loading of a page,
– or because of a browser user action,
– such as a mouse cck on a form button.
• Strictly speaking, an event is an object that
is impcitly created by the JavaScript
system in response to something
happening.

©

7.3 Introduction to Events and
Event Handng
• An event handler is a script that is impcitly
executed in response to the appearance of an
event. Event handlers enable a Web page to be
responsive to browser and user activities.
– One of the most common event handlers is to check
for simple errors and omissions in the elements of a
form either when they are changed or when the form
is submitted. This saves the time of sending the form
data to the server, where its correctness then must be
checked by a CGI program before it can be
processed.

©

7.3 Introduction to Events and
Event Handng
• If you are famiar with the exceptions and
exception-handng capabities of a
programming language such as C++ or
Java, you should see the close
relationship between events and
exceptions. Both events and exceptions
occur at unpredictable times, and both
often require some specific program
actions.

©

7.3 Introduction to Events and
Event Handng
• Because events are JavaScript objects,
their names are case-sensitive.
• The names of all event objects have only
lowercase letters.
– For example, cck is an event, but Cck is not.

©

7.3 Introduction to Events and
Event Handng
• Events are created by activities associated
with specific HTML elements.

©

7.3 Introduction to Events and
Event Handng
• Event handlers are scripts whose execution can
be triggered by the appearance of an event.
– An event handler can be specified for an event on a
specific HTML element in two different ways.
• First, an HTML tag can have an attribute that is associated
with a specific event, in which case a teral string containing
the event-handler code is assigned to that attribute. The
teral string could be a call to a function.
• Second, if the event handler is implemented as a function,
that function's name can be assigned to the JavaScript object
property associated with the event at the HTML element.
Both of these approaches are illustrated in Section 7.6,
"Event Handlers for Button Events."

©

7.3 Introduction to Events and
Event Handng
• The names of tag attributes whose values
are event handlers are not case-sensitive,
but by convention are mixed-case letters,
as in onCck. In the previous chapters, we
used the convention that tag attribute
names are written in all lowercase letters.
These conventions will make clear the
distinction between event-handler
attributes and attributes that are not
associated with handlers.

©

7.3 Introduction to Events and
Event Handng
• The write method of document should
never be used in an event handler.
– Remember that a document is displayed as
its HTML code is parsed.
– Events usually occur after the whole
document is displayed.
– If write appears in an event handler, the
content generated by it might be placed over
the top of the existing document.

©

7.4 Events, Attributes, and
Tags
• JavaScript includes a collection of events.
These events are associated with HTML
tag attributes, which can be used to
connect the events to handlers. The
attributes have names that are closely
related to their associated events. Table
7.1 sts the JavaScript events and their
associated tag attributes.

©

7.4 Events, Attributes, and
Tags
onUnload
unload
onSubmit
submit
onSelect
select
onReset
reset
on
MouseOver
mouseover
onMouseOut
mouseout
onLoad
load
onFocus
focus
onError
error
onCck
cck
onChange
change
onBlur
blur
onAbort
abort
Tag Attribute
Event
Table 7.2 page 244-246

©

7.4 Events, Attributes, and
Tags
• Some additional events—namely,
– dragdrop,
– keydown,
– keyup,
– mousedown,
– mousemove,
– mouseup,
– and move—
• are handled in more compcated ways.
These are not discussed in this chapter.

©

7.4 Events, Attributes, and
Tags
• In many cases, the same attribute can
appear in several different tags. The
circumstances under which an event is
created are related to a tag and an
attribute, and can be different for the same
attribute when it appears in a different tag.

©

7.4 Events, Attributes, and
Tags
• An HTML element is said to " get focus" when
the user puts the mouse cur -sor over it and
presses the left mouse button. An element can
also get focus when the user tabs to the element.
An element becomes blurred when the user
moves the cursor away from the element and
either presses the left button or tabs away from
the element.
• Table 7.2 shows attributes related to events,
tags that can include the attributes, and the
circumstances under which the associated
events are created.

©

7.4 Events, Attributes, and
Tags
• OnAbort
– <img>
• OnBlur
– <body>
– <frameset>
– <frame>
– <input type=“text”>
– <textarea>
– <select>

©

7.4 Events, Attributes, and
Tags
• OnChange
– <input type=“text”>
– <textarea>
– <select>
• OnCck
– <a>
– <input type=“button”>
– <input type=“submit”>
– <input type=“reset”>
– <input type=“radio”>
– <input type=“checkbox”>

©

7.4 Events, Attributes, and
Tags
• OnError
– <img>
– <body>
– <frameset>
• onFocus
– <body>
– <frameset>
– <frame>
– <input type=“text”>
– <textarea>
– <select>

©

7.4 Events, Attributes, and
Tags
• OnLoad
– <img>
– <body>
– <frameset>
• onMouseOut
– <a>
– <area>
• onMouseOver
– <a>
– <area>

©

7.4 Events, Attributes, and
Tags
• OnReset
– <form>
• OnResize
– <body>
– <frameset>
• OnSelect
– <input type=“text”>
– <textarea>
• OnSubmit
– <form>

©

7.4 Events, Attributes, and
Tags
• OnUnload
– <body>
– <frameset>
• An event handler script can be assigned
directly to a tag attribute:
onCck=“alert(‘A mouse cck has occurred! ’);”
• the teral string value of the attribute can
be just the call to the function:
onCck=“myHandler();”

©

7.5 Using the load and unload
Events
• Two of the simplest events that sometimes
require handng are the completion of the
loading and unloading of a document by
the browser. The following HTML
document, along with its embedded script,
produces alert messages for both the
loading and unloading of itself. The
onLoad and onUnload attributes of <body>
are used to specify the event handlers.
The example is meant only to illustrate in
the simplest way the use of event handng.

©

7.5 Using the load and unload
Events
• Two event-handng functions are used,
one for the onload event and one for the
onunload event. Although it is legal to
include the handler code in the attribute
value, we prefer to write handlers as
functions.
Sample Ch7_1.html

©

7.6 Event Handlers for Button
Events
• Buttons on a Web page provide a simple
and effective way to collect multiple-choice
input from the browser user. Consider the
following example of a set of radio buttons
that enables the user to choose
information about a specific air-plane. The
cck event is used in this example to
trigger a call to alert, which presents a
brief description of the selected airplane.
Sample Ch7_2.html

©

7.6 Event Handlers for Button
Events
• You could refer to the form elements
through the forms and elements arrays.
For example, the one ck property
associated with the first button in the radio
button collection in the previous example
can be assigned the event handler with
the statement:
• document.planesForm.elements[0].oncck
= planeChoice;
Sample Ch7_2x.html

©

7.6 Event Handlers for Button
Events
• There is no way to specify parameters, on
the handler function when it is assigned to
the event property. Therefore, eventhandler
functions that are used this way
must not use parameters. This is clearly a
disadvantage of this approach.

©

7.6 Event Handlers for Button
Events
• There are two advantages to specifying handlers
as properties over specifying them in HTML
attributes.
– First, it is good to keep HTML and JavaScript
separated in the document. This allows a kind of
modularization of HTML documents, resulting in a
cleaner design that will be easier to maintain.
– Second, having the handler function specified as the
value of a property allows for the possibity of
changing it during use, which would be impossible if it
were connected to an element in HTML.

©

7.7 Checking Form Input
• As started earer, checking the format and
completeness of form input is a common
appcation of JavaScript. This shifts this
task from the usually busy server to the
cent, which in most cases is only ghtly
used. It also results in less network traffic
and allows quicker responses to users.

©

7.7 Checking Form Input
• 7.7.1 EVENT HANDLERS FOR FORM INPUT
CHECKING
• When a user fills in a form input element incorrectly and
a JavaScript event-handler function detects the error, the
function should do several things.
– First, it should produce an alert message indicating the error to
the user and specifying the correct format of the input.
– Next, it should cause the input element to be put in focus, which
positions the cursor in the element. This is done with the focus
function, which must be called through the DOM address of the
element.
For example, if the form's name is myForm and the element's
name is phone, the element can be put in focus with this
statement:
document.myForm.phone.focus ();

©

7.7 Checking Form Input
– Finally, the function must select the element, which
highghts the text in the element. This is done with
the select function, as in this example:
document.myForm.phone.select();
• If you want the form to remain active after an
event-handng function completes its execution,
the function must return false.
• If an event-handng function that has checked a
form input and found its format to be correct
completes its execution, it must return true.

©

7.7 Checking Form Input
• 7.7.2 AN EXAMPLE: COMPARING
PASSWORDS
• When a form requests a password from
the user and that password will be used in
future sessions, the user is often asked to
enter the password a second time for
verification. A JavaScript function can be
used to check that the two entered
passwords are the same.

©

7.7 Checking Form Input
• The form for this example includes the two password
input elements, along with Reset and Submit buttons.
The form and the two password input ele-ments are
named. The JavaScript function that checks the
passwords does its job when the Submit button is
pressed, using the onsubmit event to trigger the call. The
function performs two different tests.
– First, it determines whether the user typed the initial password
by testing the value of the element against the empty string. If no
password has been typed into the first field the function calls
focus on the field and returns false.
– The second test is to deter-mine whether the two typed
passwords are the same. If they are different the function calls
both focus and select on the first password field and returns false.
If they are the same, it returns true.
Sample Ch7_3.html

©

7.7 Checking Form Input
• 7.7.3 ANOTHER EXAMPLE: FORM
INPUT CHECKING
• In the example of this section, the name
and phone number of the user are
socited through text boxes. Fucntions are
used to check the form of each input when
the values of the text boxes are changed,
which is detected by the appearance of
the change event.
Sample Ch7_4.html

©

7.8 The navigator Object
• The navigator object indicates which browser is
being used to view the HTML document. The
browser's name is stored in the appName
property of the navigator object. The version of
the browser is stored in the appVersion property
of the navigator object. These allow the script to
determine which browser is being used and to
use processes appropriate to that browser. The
following example illustrates the use of navigator,
in this case just to display the browser name and
version number.
Sample Ch7_5.html

©

7.9 Event Propagation
• Another idea in event handng that has been borrowed
from exception handng is event propagation. In a large
and compcated document, having event handlers for
every element creates a great deal of code. Much of this
code would be redundant, both in the handlers and in the
specifications of handlers for events. Therefore, it makes
sense to define a way for a single handler to deal with
events created from a number of similar elements. The
concept is that events can be propagated to some
central place for handng rather than always being
handled locally. In DOM, the natural central place for
event handng is at the document or window level.

©

7.9 Event Propagation
• The DOM 2 model of event propagation, in which the
propagation is called bubbng, allows events to be
handled at the element level, but they can also bubble
up toward the document level for handng. Two
categories of events exist: those that bubble and those
that do not. Among the events discussed in this chapter,
the following do not bubble: load, unload, focus, and blur.
The others do. The events that are allowed to bubble do
that unless a handler specifically tells the system not to
bubble them, which is done by calng the
stopPropagation method. If only one element in the DOM
hierarchy has a handler for a particular event, bubbng
has no effect other than to ensure that the event gets to
the handler.
• The IE5 and NN6 browsers support event bubbng,
although NN4 does not.

©

7.10 Summary
• The highest levels of the execution
environment of cent-side JavaScript are
represented with the Window and
Document objects. The Document object
includes a forms array property, which
includes references to all forms in the
document. Each element of the forms
array has an elements array, which
includes references to all elements in the
form.

©

7.10 Summary
• DOM is an abstract interface whose
purpose is to provide a languageinde-
pendent way to access the elements
of an HTML document. Also included are
the means to navigate around the
structure in which the HTML elements
appear. HTML tags are represented in
JavaScript as objects; tag attributes are
represented as properties. Browser
support for the DOM is now far more
universal than in the past.

©

7.10 Summary
• Events are simply notifications that something
specific has happened that may require some
special processing. Event-handng code
provides that special processing. There are two
ways to associate an event handler with the
appear-ance of a particular event from a
particular HTML element. First, an attribute of
the tag that defines the HTML element can be
assigned the handler code. Second, the property
associated with the event on the object that
represents the HTML element can be assigned
the name of a function that implements the
handler. The write method of document should
not be used in event han -dlers.

©

7.10 Summary
• Each event has an associated tag attribute. A
particular attribute may appear in several
different tags. Each of these appearances is
identified as a different event occurrence. The
load and unload events are often used with the
<body> tag to signify that a document has been
loaded or unloaded, respectively. The cck
event is used for all of the different HTML
buttons, as well as the nk of an anchor tag.
Form input can be conveniently checked using
the change event. The submit event can also be
used to check form data just before the form is
submitted.

©

7.10 Summary
• The navigator object has information about
which browser is being used, as well as its
version number and other related
information.

©

7.11 Review Questions
• 1. Global variables in JavaScript are properties of what
object?
• 2. How are HTML elements and attributes represented in
the JavaScript binding to DOM?
• 3. What is an event?
• 4. What is an event handler?
• 5. What are the two ways in which an event handler can
be associated with an event generated by a specific
HTML element?
• 6. Why should document .write not be used in an event
handler?
• 7. How can an HTML element acquire focus?
• 8. What is the disadvantage of assigning event handlers
to event properties?

©

7.11 Review Questions
• 9. What are the advantages of assigning event handlers
to event properties?
• 10. Why is it good to use JavaScript to check the vadity
of form inputs before the form data is sent to the server?
• 11. What three things should be done when a form input
element is found to have incorrectly formatted data?
• 12. What exactly does the focus function do?
• 13. What exactly does the select function do?
• 14. What happens when an event handler for the
onsubmit event returns false?
• 15. What event is used to trigger an event handler that
checks the vadity of input to a text button in a form?
• 16. What purpose does the navigator object have?
• 17 What is event bubbng?

©

7.12 Exercises
• Page 264
– 1
– 3
– 5

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭