Tài liệu Web Programming with HTML, XHTML, and CSS Second Edition- P10 - Pdf 87

4.
Save this example as
ch11_eg4.html
and open it in your browser. Then roll your mouse over
the image (without clicking it). You should see something like Figure 11-5 with the mouse
over the image.
Figure 11-5
How It Works
When the user rolls over the image, the
onmouseover
event fires, and when the user moves off it again
the
onmouseout
event fires. This is why there are separate attributes that correspond to each of these
events, and when one of these two events fires, the script held as a value for the corresponding attribute
is executed.
The script in the
onmouseover
and
onmouseout
event handler attributes tells the browser to change the
src
attribute of the image, and therefore a different image is displayed to the user.
The first (
onmouseover
) indicates what should happen when the mouse is placed over the image; the
second (
onmouseout
) indicates what should be done when the mouse is moved off the image.
You can see in the code for
ch11_eg04.html

You will come across several types of objects in JavaScript, each of which is responsible for a related set
of functionalities. For example, the document object has methods and properties that relate to the docu-
ment; the forms collection, which is part of the document object, deals with information regarding forms;
and so on. As you are about to see, there can be lots of different objects, each of which deals with a differ-
ent set of functionalities and properties.
So, here are some of the types of objects you are likely to come across:
❑ W3C DOM objects: These are like those covered already in this chapter, although in more recent
browsers there are several more objects that are made available to allow you more control over a
document. There are also additional objects in each different level of the DOM released by the W3C.
❑ Built-in objects: Several objects are part of the JavaScript language itself. These include the date
object, which deals with dates and times, and the math object, which provides mathematical
functions. You will be learning more about these built-in objects later in the chapter.
❑ Custom objects: If you start to write advanced JavaScript you might even start creating your own
JavaScript objects that contain related functionality; for example, you might have a validation object
that you have written just to use to validate your forms.
While it is not possible to cover the creation of custom objects in this chapter, you learn about the built-in
objects later in this chapter.
Starting to Program with JavaScript
Having learned about the DOM, you can see how it allows you to access a document in a web browser.
However, it is JavaScript that introduces real programming concepts. You know that the DOM allows
you to retrieve and set properties, and that methods can be used to evoke actions such as writing new
content to a page. Now it is time to look at how you use these values and properties in scripts to create
more powerful documents.
As I mentioned earlier, a programming language mainly performs calculations. So here are the key concepts
you need to learn about in order to perform different types of calculations:
❑ A variable is used to store some information; it’s like a little bit of memory where you can store
numbers, strings (which are a series of characters), or references to objects. You can then per-
form calculations to alter the data held in variables within your code.
❑ Operators allow you to do things to variables or references to. There are different types of opera-
tors. For example:

the week.
The following section looks at these key concepts in more detail.
Variables
Variables are used to store data. To store information in a variable, you can give the variable a name and
put an equal sign between it and the value you want it to have. For example, here is a variable that con-
tains a username:
userName = “Bob Stewart”
The variable is called
userName
and the value is
Bob Stewart
. If no value is given, then its value is unde-
fined. (Note that when you are writing out the value of the variable in the code, the value is given in quo-
tation marks.)
When you first use a variable, you are creating it. The process of creating a variable is referred to as declaring
the variable. You can declare a variable with the
var
statement, like so:
var userName = “Bob Stewart”
I should note here that you need to use the
var
keyword only if you are creating a variable inside a
function that has the same name as a global variable — although to understand this point you need
to understand functions and global and local variables, which are covered later.
A variable’s value can be recalled or changed by the script, and when you want to do either of these you
use its name.
There are a few rules you must remember about variables in JavaScript:
❑ Variable names are case-sensitive.
❑ They must begin with a letter or the underscore character.
423

The operator itself is a keyword or symbol that does something to a value when used in an expression. For
example, the arithmetic operator
+
adds two values together.
The symbol is used in an expression with either one or two values and performs a calculation on the values
to generate a result. For example, here is an expression that uses the
x
operator:
area = (width x height)
An expression is just like a mathematical expression. The values are known as operands. Operators that
require only one operand (or value) are sometimes referred to as unary operators, while those that require
two values are sometimes called binary operators.
424
Chapter 11: Learning JavaScript
59313c11.qxd:WroxPro 3/23/08 1:21 PM Page 424
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
The different types of operators you will see in this section are:
❑ Arithmetic operators
❑ Assignment operators
❑ Comparison operators
❑ Logical operators
❑ String operators
You will see lots of examples of the operators in action both later in this chapter and in the next chapter.
First, however, it’s time to learn about each type of operator.
Arithmetic Operators
Arithmetic operators perform arithmetic operations upon operands. (Note that in the examples in the
following table, x = 10.)
Assignment Operators
The basic assignment operator is the equal sign, but do not take this to mean that it checks whether two
values are equal. Rather, it’s used to assign a value to the variable on the left of the equal sign, as you

x++
11
--
Decrement (decreases the variable by 1)
x--
9
425
Chapter 11: Learning JavaScript
59313c11.qxd:WroxPro 3/23/08 1:21 PM Page 425
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
This can be reduced to the following statement:
total -= profit
While it might not look like much, this kind of shorthand can save a lot of code if you have a lot of calcu-
lations such as this (see table below) to perform.
Comparison Operators
As you can see in the table that follows, comparison operators compare two operands and then return
either
true
or
false
based on whether the comparison is true or not.
Note that the comparison for checking whether two operands are equal is two equal signs (a single equal
sign would be an assignment operator).
Operator Description Example
== Equal to 1==2 returns
false
3==3 returns
true
!= Not equal to 1!=2 returns
true

/= x/=y x=x/y
%= x%=y x=x%y
426
Chapter 11: Learning JavaScript
59313c11.qxd:WroxPro 3/23/08 1:21 PM Page 426
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Logical or Boolean Operators
Logical or Boolean operators return one of two values:
true
or
false
. They are particularly helpful
because they allow you to evaluate more than one expression at a time.
The two operands in a logical or Boolean operator evaluate to either
true
or
false
. For example, if
x=1
and
y=2
, then
x<2
is
true
and
y>1
is
true
. So the following expression:

And Allows you to check if both of
two conditions are met
(x < 2 && y > 1)
Returns
true
(because both
conditions are met)
??
Or Allows you to check if one of two
conditions are met
(x < 2 ??y < 2)
Returns
true
(because the first
condition is met)
!
Not Allows you to check if something
is not the case
! (x > y)
Returns
true
(because x is not
more than y)
427
Chapter 11: Learning JavaScript
59313c11.qxd:WroxPro 3/23/08 1:21 PM Page 427
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
How to Define a Function
There are three parts to creating or defining a function:
❑ Define a name for it.

Enter the width and height of your rectangle to calculate the size:<br />
Width: <input type=”text” name=”txtWidth” size=”5” /><br />
Height: <input type=”text” name=”txtHeight” size=”5” /><br />
<input type=”button” value=”Calculate area”
onclick=”alert(calculateArea(document.frmArea.txtWidth.value,
document.frmArea.txtHeight.value))” />
</form>
Take a closer look at what is happening when the
onclick
event fires. First a JavaScript alert is being
called, and then the
calculateArea()
function is being called inside the alert, so that the area is the
value that is written to the alert box. Inside the parentheses where the
calculateArea()
function is
being called, the two parameters being passed are the values of the width text box and the height text
box using the dot notation you learned early in the section on the DOM.
Note that if your function has no arguments you still need to use the parentheses at the end of the func-
tion name when you call it; for example, you might have a function that will run without any extra infor-
mation passed as an argument:
<input type=”submit” onClick=”exampleFunction()” />
428
Chapter 11: Learning JavaScript
59313c11.qxd:WroxPro 3/23/08 1:21 PM Page 428
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
The Return Statement
Functions that return a result must use the
return
statement. This statement specifies the value that will

statements, which are used when you want to execute one set of code if a condition
is true and another if it is false

switch
statements, which are used when you want to select one block of code from many
depending on a situation
if Statements
if
statements allow code to be executed when the condition specified is true; if the condition is true then
the code in the curly braces is executed. Here is the syntax for an
if
statement:
if (condition)
{
code to be executed if condition is true
}
For example, you might want to start your home page with the text “Good Morning” if the time is in the
morning. You could achieve this using the following script (
ch11_eg06.html
):
<script type=”text/JavaScript”>
date = new Date();
time = date.getHours();
if (time < 12) {
document.write(‘Good Morning’);
}
</script>
429
Chapter 11: Learning JavaScript
59313c11.qxd:WroxPro 3/23/08 1:21 PM Page 429

Returning to the previous example, you can write
Good Morning
if the time is before noon, and
Good
Afternoon
if it is after noon (
ch11_eg07.html
).
<script type=”text/JavaScript”>
date = new Date();
time = date.getHours();
if (time < 12) {
document.write(‘Good Morning’);
}
else {
document.write(‘Good Afternoon’);
}
</script>
As you can imagine there are a lot of possibilities for using conditional statements. Indeed, you will see
examples in Chapter 12 that include several such statements to create some very powerful and complex
examples.
430
Chapter 11: Learning JavaScript
59313c11.qxd:WroxPro 3/23/08 1:21 PM Page 430
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
A switch Statement
A
switch
statement allows you to deal with several results of a condition. You have a single expression,
which is usually a variable. This is evaluated immediately. The value of the expression is then compared

<p>Enter the name of your favorite type of animal that stars in a cartoon:</p>
<form name=”frmAnimal”>
<input type=”text” name=”txtAnimal” /><br />
<input type=”button” value=”Check animal” onclick=”checkAnimal()” />
</form>
Here is the function that contains the
switch
statement:
function checkAnimal() {
switch (document.frmAnimal.txtAnimal.value){
case “rabbit”:
alert(“Watch out, it’s Elmer Fudd!”)
break;
case “coyote”:
alert(“No match for the road runner - meep meep!”)
break;
case “mouse”:
alert(“Watch out Jerry, here comes Tom!”)
break;
default : alert(“Are you sure you picked an animal from a cartoon?”);
}
}
431
Chapter 11: Learning JavaScript
59313c11.qxd:WroxPro 3/23/08 1:21 PM Page 431
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
The final option — the default — is shown if none of the cases are met. You can see what this would look
like when the user has entered rabbit into the text box in Figure 11-6.
Note that, should the user enter text in a different case, it will not match the options in the
switch

while
loop runs the same block of code while or until a condition is true.
432
Chapter 11: Learning JavaScript
59313c11.qxd:WroxPro 3/23/08 1:21 PM Page 432
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
❑ A
do while
loop runs once before the condition is checked. If the condition is true, it will con-
tinue to run until the condition is false. (The difference between the
do
and
do while
loops is
that
do while
runs once whether or not the condition is met.)
❑ A
for
loop runs the same block of code a specified number of times.
while
In a
while
loop, a code block is executed if a condition is true and for as long as that condition remains
true. The syntax is as follows:
while (condition)
{
code to be executed
}
In the following example, you can see a

do . . . while
A
do ... while
loop executes a block of code once and then checks a condition. For as long as the con-
dition is true it continues to loop. So, whatever the condition, the loop runs at least once (as you can see
the condition is after the instructions). Here is the syntax:
do
{
code to be executed
}
while (condition)
For example, here is the example with the 3 multiplication table again — the counter is set with an initial
value of 12, which is higher than required in the condition, so you will see the sum 12 × 3 = 36 once, but
nothing after that (because when it comes to the condition, it has been met):
<script type=”text/JavaScript”>
i = 12
do {
document.write(i + “ x 3 = “ + (i * 3) + “<br />” );
i ++
}
while (i < 11)
</script>
Now, if you changed the value of the initial counter to 1 you would see that the script loops through the
multiplication table as it did in the last example until it gets to 11.
for
The
for
statement executes a block of code a specified number of times; you use it when you know how
many times you want the code to be executed (rather than running while a particular condition is true/
false). First, here is the syntax:

Chapter 11: Learning JavaScript
59313c11.qxd:WroxPro 3/23/08 1:21 PM Page 434
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
So if you come back to the 3 multiplication table example again, it would be written something like this:
for (i=0; i<11; i++) {
document.write(i + “ x 3 = “ + (i * 3) + “<br />” );
}
The
a
is where the counter is assigned to have a value of 0,
b
is where the condition is saying that the
loop should run if the value of the counter is less than 11, and
c
is where the counter is incremented by 1
every time the loop runs. The assignment of the counter variable, the condition, and the incrementing of
the counter all appear in the parentheses after the keyword
for
.
You can also assign several variables at once in the part corresponding to the letter
a
if you separate them
with a comma. For example,
i=0,j=5;
.
Infinite Loops and the break Statement
Note that, if you have an expression that always evaluates to
true
in any loop, you end up with something
known as an infinite loop. These can tie up system resources and can even crash the computer, although some

435
Chapter 11: Learning JavaScript
59313c11.qxd:WroxPro 3/23/08 1:21 PM Page 435
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
an attribute. The value of the attribute is the script that should be executed when the event occurs on that
element (this could call a function in the
<head>
of the document).
For example, the
onmouseover
and
onmouseout
events can be used to change an image’s source attribute
and create a simple image rollover, as you saw earlier in the chapter:
<a href=””
onmouseover=”document.images.link.src=’images/click_red.gif’;”
onmouseout=”document.images.link.src=’images/click_green.gif’”>
<img src=”images/click_green.gif” width=”100” height=”50” border=”0”
name=”link”>
</a>
The table that follows provides a recap of the most common events you are likely to come across.
Event Purpose Applies To
onload
Document has finished loading (if used in a
frameset, all frames have finished loading).
<body> <frameset>
onunload
Document is unloaded, or removed, from a
window or frameset.
<body> <frameset>

A key is pressed and released over the
element.
Most elements
onkeydown
A key is held down over an element. Most elements
onkeyup
A key is released over an element. Most elements
436
Chapter 11: Learning JavaScript
59313c11.qxd:WroxPro 3/23/08 1:21 PM Page 436
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
You will see examples of these events used throughout this and the next chapter. You can also check which
elements support which methods in Chapters 1 through 6 as those elements are discussed; almost every
element can be associated with an event.
Built-in Objects
You learned about the document object at the beginning of the chapter and now it is time to see some of
the objects that are built-in JavaScript objects. You will see the methods that allow you to perform actions
upon data, and properties that tell you something about the data.
String
The string object allows you to deal with strings of text. Before you can use a built-in object you need to cre-
ate an instance of that object. You create an instance of the string object by assigning it to a variable like so:
myString = new String(‘Here is some big text’)
The string object now contains the words “Here is some big text.” Once you have this object in a variable
you can write the string to the document or perform actions upon it. For example, the following method
writes the string as if it were in a
<big>
element:
document.write(myString.big())
All of the properties and methods in this section are supported in Netscape 2 and IE3
or higher browsers unless otherwise stated.

59313c11.qxd:WroxPro 3/23/08 1:21 PM Page 437
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Note that if you viewed the source of this element, it would not actually have the
<big>
element in it;
rather you would see the JavaScript, so that a user who did not have JavaScript enabled would not see
these words at all.
You can check the length of this property like so:
alert(myString.length)
Before you can use the string object, remember you first have to create it and then give it a value.
Properties
The following table shows the main property for the String object and its purpose.
Methods
The following table lists the methods for the String object and their purposes.
Method Purpose
anchor(name)
Creates an anchor element (an
<a>
element with a
name
or
id
attribute rather than an
href
attribute).
big()
Displays text as if in a
<big>
element.
bold()

searchValue
inside another string. For example, if you have the
word “banana” as your string, and you want to find the first
occurrence of the letter
n
, you use
indexOf(n)
.
If the
fromIndex
argument is used, the search will begin at that
index. For example, you might want to start after the fourth
character.
The method returns
-1
if the string being searched for never occurs.
Property Purpose
length
Returns the number of characters in a string
438
Chapter 11: Learning JavaScript
59313c11.qxd:WroxPro 3/23/08 1:21 PM Page 438
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Try It Out Using the String Object
In this example, you see a subsection of a string collected and turned into all uppercase letters. From the
text “Learning about Built-in Objects is easy,” this example will just collect the words “Built-in objects”
and turn them into uppercase characters.
1.
Create a skeleton XHTML document, like so:
<?xml version=”1.0” ?>

element.
strike()
Displays text as if in a
<strike>
element.
sub()
Displays text as if in a
<sub>
element.
substr(start}, [length])
Returns the specified characters. 14,7 returns 7 characters, from
the 14
th
character (starts at 0).
Note that this works only in IE4 and Netscape 4 and later versions.
substring(startPosition,
endPosition)
Returns the specified characters between the start and end
index points. 7,14 returns all characters from the 7
th
up to but
not including the 14
th
(starts at 0).
sup()
Displays text as if in a
<sup>
element.
toLowerCase()
Converts a string to lowercase.

Objects is easy
. But, the idea of this exercise was just to select the words “Built-in Objects” so you
use the
substring()
method. The syntax is as follows:
substring(startPosition, endPosition)
So you select the string object (which is in the variable
myString
) and make its value the new substring
you want (this is reassigning the value with the substring we want):
myString = myString.substring(15, 32)
This selects the string from the 16
th
character to the 33
rd
character — because it starts at position 0.
Next you must convert the string to uppercase using the
toUpperCase()
method:
myString = myString.toUpperCase()
And finally you can write it to the document like so:
document.write(myString)
The result looks quite simple, but when you consider the original string was
Learning about Built-in
Objects is easy
it now looks substantially different.
440
Chapter 11: Learning JavaScript
59313c11.qxd:WroxPro 3/23/08 1:21 PM Page 440
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status