1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning JavaScript Third Edition phần 8 ppt

79 321 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Beginning JavaScript Third Edition phần 8 ppt
Trường học University of Example
Chuyên ngành Computer Science / Web Development
Thể loại Lecture Notes
Năm xuất bản 2023
Thành phố Hà Nội
Định dạng
Số trang 79
Dung lượng 1,5 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

toolbar-Padding Border Both elements 30 pixels in height and width Padding 530 Chapter 13: Dynamic HTML in Modern Browsers... function button_mouseHandler{ var eType = event.type; var

Trang 1

Figure 13-15

This is a side-by-side comparison of the toolbar-buttonand toolbar-button-hoverclasses Thetoolbar-buttonclass is 24 pixels in height and width plus three pixels of padding per side Thatmakes toolbar-button30 pixels in height and width

The toolbar-button-hoverclass starts with the same 24 pixels in height and width You then add aone-pixel border, which adds two pixels to the height and width Then you add two pixels of padding

on each side, which makes toolbar-button-hover30 pixels in height and width, just like button If you used three pixels of padding instead of two in toolbar-button-hover, the buttonwould grow in size when the mouse pointer hovered over it, as Figure 13-16 shows

toolbar-Padding

<div/>

<div/>

Border

Both elements 30 pixels

in height and width

Padding

530

Chapter 13: Dynamic HTML in Modern Browsers

Trang 2

display: inline-block;

height: 24px;

width: 24px;

}You can now slim down the toolbar-buttonand toolbar-button-hoverclasses:

.toolbar-button {

padding: 3px;

}.toolbar-button-hover {

border: 1px solid #316AC5;

background-color: #C1D2EE;

padding: 2px;

cursor: pointer;

}

By making this change, you can easily add style that is shared by both states

The last property we’ll discuss for the button is the cursorproperty The mouse cursor (or pointer) is animportant user interface component It can tell the user when something is going on in the background

or let him know when he can highlight text It also changes to a hand when he moves the cursor over alink, letting him know that something will happen when he clicks it

Padding

531

Chapter 13: Dynamic HTML in Modern Browsers

Trang 3

As stated earlier, you want the user to understand what the toolbar is and what it does By using thecursorproperty and setting it to pointer, you show the user a hand when he moves his mouse over abutton This offers the suggestion “Hey you! You can click me!”

Styling the Icons

The last style rule you need to write is one for the icons These are simple <img/>elements with a CSSclass name of toolbar-icon

Storing Button Information

You need some way to store the button information In this script, you’ll use a multi-dimensional array

to contain information for specific buttons Let’s start with the first array Let’s call it myToolbar.var myToolbar = new Array();

Each element in this array, myToolbar[x], will also be declared as an array Each of these inner arrayswill hold information for a particular button

You start this process with the array element of index 0

myToolbar[0] = new Array();

Now you can use the elements of this array, namely myToolbar[0][0]and myToolbar[0][1], to holdinformation about the first button That information will be the image location for the icon and the page(or JavaScript code) to load when the button is clicked So you see that the following code holds the loca-tion of the icon:

myToolbar[0][0] = “img/green.gif”;

The next line holds the web location, or JavaScript code, to load

myToolbar[0][1] = “javascript: alert(‘You Clicked the Green Button!’)”;

Each button follows this pattern of defining a new Arrayobject and inserting it in the first dimension.Then you make the second dimension of the array hold the icon information and the link or JavaScriptcode to load

myToolbar[0] = new Array();

myToolbar[0][0] = “img/green.gif”;

myToolbar[0][1] = “javascript: alert(‘You Clicked the Green Button!’)”;

myToolbar[1] = new Array();

532

Chapter 13: Dynamic HTML in Modern Browsers

Trang 4

myToolbar[1][0] = “img/blue.gif”;

myToolbar[1][1] = “javascript: alert(‘You Clicked the Blue Button!’)”;

myToolbar[2] = new Array();

myToolbar[2][0] = “img/red.gif”;

myToolbar[2][1] = “http://www.wrox.com”;

Building the Toolbar

You need a function to build the toolbar and populate it with buttons Let’s write a function calledcreateToolbar()that will do that for you It needs to accept two arguments: the first one is the name

of your toolbar, and the second is your multi-dimensional array containing the button information Youknow how the HTML should be structured, so let’s get started

The first step is to dynamically create the <div/>element for the toolbar

function createToolbar(sName, aItems){

var toolbar = document.createElement(“div”);

You now have an empty toolbar, so you need to use the myToolbararray to populate it with buttons.You’ll do this with a forloop

function createToolbar(sName, aButtons){

var toolbar = document.createElement(“div”);

toolbar.id = sName;

toolbar.className = “toolbar”;

for (var i = 0; i < aButtons.length; i++){

var thisButton = aButtons[i];

var button = document.createElement(“span”);

var icon = document.createElement(“img”);

//more code here}

Trang 5

Inside the loop, you get the element of the array that corresponds to this button and assign it to

thisButton This enables you to easily access the button’s information Then you create the required

<span/>and <img/>elements The button variable references the <span/>element, and the icon able references the <img/>element

vari-Next, add the hrefattribute to buttonwith the setAttribute()method The value of this attribute iscontained in the thisButton[1]element of the thisButtonarray Also set the CSS class

function createToolbar(sName, aButtons)

var thisButton = aButtons [i];

var button = document.createElement(“div”);

var icon = document.createElement(“img”);

Handling User Interaction

User interaction is an important part of DHTML; you usually want your HTML to react to something auser does, and the toolbar is no exception As already mentioned, there are three areas of user interactionyou want to handle:

❑ When the user moves her mouse pointer over a button

❑ When the user moves her mouse pointer off a button

❑ When the user clicks a button

You’ll write one function to handle these events: button_mouseHandler()

534

Chapter 13: Dynamic HTML in Modern Browsers

Trang 6

The button_mouseHandler() Function

Using one function to handle the three mouse events is a time- and code-saving measure, especially inthe case of this DHTML script The function begins with its definition and two variables:

function button_mouseHandler(){

var eType = event.type;

var eSrc = event.srcElement;

//more code here}

This DHTML script is quite similar to the image rollover scripts you wrote in the previous chapter Here,you’re concerned only with the element that the event was fired upon (the source element) and the eventtype that called the event handler The next step is to write the code for the mouseoverevent

function button_mouseHandler(){

var eType = event.type;

var eSrc = event.srcElement;

if (eType == “mouseover”){

eSrc.className = “toolbar-button-hover”;

}//more code here}

This code checks to see if the event type is a mouseoverevent, and, if so, it changes the source element’sclassNameproperty to toolbar-button-hover

Now it’s time to handle the mouseoutevent When the mouse pointer leaves the button, the desiredeffect is to return the previously highlighted button to its original state Therefore, the following codechanges the classNameproperty of the source element (of the mouseoutevent) back to toolbar-button

function button_mouseHandler(){

var eType = event.type;

var eSrc = event.srcElement;

if (eType == “mouseover”){

eSrc.className = “toolbar-button-hover”;

}else if (eType == “mouseout”){

eSrc.className = “toolbar-button”;

}//more code here}

535

Chapter 13: Dynamic HTML in Modern Browsers

Trang 7

Now things are beginning to take shape When the mouse pointer moves over the button, its stylechanges to give a highlight effect, and the mouse pointer leaving the button returns it to its originalstate Now you need to write the code to handle the clickevent, and the following code does this:function button_mouseHandler()

{

var eType = event.type;

var eSrc = event.srcElement;

//more code here

if (eType == “mouseover”){

eSrc.className = “toolbar-button-hover”;

}else if (eType == “mouseout”){

eSrc.className = “toolbar-button”;

}else if (eType == “click”){

eSrc.className = “toolbar-button”;

window.location.href = eSrc.getAttribute(“href”);

}}

The code handling the clickevent does two things First, it returns the clicked button’s classNameproperty back to toolbar-button, and second, it navigates to the desired web page, or executesJavaScript code

But alas, all is not well If you were to run this code, you would notice a few weird things happening.Buttons would highlight and unhighlight at strange times, the icons would grow to the size of the but-tons, and you’d see some very strange results if you clicked on a button when the mouse pointer wasover an icon (the browser would navigate to the URL specified in the <img/>element’s srcproperty).These behaviors may seem weird, but they are normal As the mouse pointer moves over the <img/>element, it is no longer over the <span/>element (the button) Therefore, the mouseoutevent fires asthe mouse leaves the <span/>and enters the <img/>

A simple solution to this problem is to check the source element’s tagNameproperty, and, if it’s IMG, toaccess the image’s parent node: the <span/>element that represents the button

function button_mouseHandler()

{

var eType = event.type;

var eSrc = event.srcElement;

if (eSrc.tagName == “IMG”){

Trang 8

{eSrc.className = “toolbar-button-hover”;

}else if (eType == “mouseout”){

eSrc.className = “toolbar-button”;

}else if (eType == “click”){

eSrc.className = “toolbar-button”;

window.location.href = eSrc.getAttribute(“href”);

}}Now the eSrcvariable will always reference the <span/>element, making the button behave as youwould expect it to

var thisButton = aButtons[i];

var button = document.createElement(“span”);

var icon = document.createElement(“img”);

}Now the code for the toolbar is complete You have the toolbar, you populated it with buttons, and youadded interactivity for those buttons Now you need only to call createToolbar()

537

Chapter 13: Dynamic HTML in Modern Browsers

Trang 9

Finishing Up

Creating a toolbar is easy; however, there is one caveat you must consider Since you generate the HTMLelements dynamically and append them to document.body, you must create the toolbar while the docu-ment is loading, or after the document is loaded If you attempt to load the toolbar at any other time,you’ll get errors in your page

In this exercise, you’ll use the onloadevent handler to create the toolbar after the document is loaded.Following is the complete source code for the toolbar DHTML script Open the text editor of your choiceand type the following:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”

background-color: #E4E2D5;

padding: 2px;

}.toolbar span {

display: inline-block;

height: 24px;

width: 24px;

}.toolbar-button {

padding: 3px;

}.toolbar-button-hover {

border: 1px solid #316AC5;

background-color: #C1D2EE;

padding: 2px;

cursor: pointer;

}.toolbar-icon {

var eType = event.type;

538

Chapter 13: Dynamic HTML in Modern Browsers

Trang 10

var eSrc = event.srcElement;

if (eSrc.tagName == “IMG”){

eSrc = eSrc.parentNode;

}

if (eType == “mouseover”){

eSrc.className = “toolbar-button-hover”;

}else if (eType == “mouseout”){

eSrc.className = “toolbar-button”;

}else if (eType == “click”){

eSrc.className = “toolbar-button”;

window.location.href = eSrc.getAttribute(“href”);

}}function createToolbar(sName, aButtons) {var toolbar = document.createElement(“div”);

toolbar.id = sName;

toolbar.className = “toolbar”;

for (var i = 0; i < aButtons.length; i++){

var thisButton = aButtons[i];

var button = document.createElement(“span”);

var icon = document.createElement(“img”);

}var myToolbar = new Array();

myToolbar[0] = new Array();

myToolbar[0][0] = “img/green.gif”;

539

Chapter 13: Dynamic HTML in Modern Browsers

Trang 11

myToolbar[0][1] = “javascript: alert(‘You Clicked the Green Button!’)”;

myToolbar[1] = new Array();

myToolbar[1][0] = “img/blue.gif”;

myToolbar[1][1] = “javascript: alert(‘You Clicked the Blue Button!’)”;

myToolbar[2] = new Array();

DHTML Example: The Toolbar in F irefox and Opera

Writing the toolbar script for Firefox is surprisingly easy, as most of the code can be reused As you’vealready learned, IE and Firefox share many similarities, but they greatly differ in their event models

The toolbar script follows this same pattern You’ll have to make a change in the CSS and change theevent handlers to work with the DOM event model, but other than that your code will remain

unchanged

540

Chapter 13: Dynamic HTML in Modern Browsers

Trang 12

Try It Out The Toolbar in Firefox and OperaOpen your text editor of choice and type the following:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”

background-color: #E4E2D5;

padding: 2px;

}.toolbar span {

padding: 3px;

}.toolbar-button-hover {

border: 1px solid #316AC5;

background-color: #C1D2EE;

padding: 2px;

cursor: pointer;

}.toolbar-icon {

var eType = e.type;

var eSrc = e.target;

if (eSrc.tagName == “IMG”){

eSrc = eSrc.parentNode;

541

Chapter 13: Dynamic HTML in Modern Browsers

Trang 13

if (eType == “mouseover”){

eSrc.className = “toolbar-button-hover”;

}else if (eType == “mouseout”){

eSrc.className = “toolbar-button”;

}else if (eType == “click”){

eSrc.className = “toolbar-button”;

window.location.href = eSrc.getAttribute(“href”);

}}function createToolbar(sName, aButtons){

var toolbar = document.createElement(“div”);

toolbar.id = sName;

toolbar.className = “toolbar”;

for (var i = 0; i < aButtons.length; i++){

var thisButton = aButtons[i];

var button = document.createElement(“span”);

var icon = document.createElement(“img”);

}var myToolbar = new Array();

myToolbar[0] = new Array();

Trang 14

myToolbar[1][0] = “img/blue.gif”;

myToolbar[1][1] = “javascript: alert(‘You Clicked the Blue Button!’)”;

myToolbar[2] = new Array();

.toolbar span {

Now let’s jump to the mouse event handler The primary changes made to the function are the values ofthe eTypeand eSrcvariables, as well as an added parameter

543

Chapter 13: Dynamic HTML in Modern Browsers

Trang 15

function button_mouseHandler(e)

{

var eType = e.type;

var eSrc = e.target;

if (eSrc.tagName == “IMG”){

eSrc = eSrc.parentNode;

}

if (eType == “mouseover”){

eSrc.className = “toolbar-button-hover”;

}else if (eType == “mouseout”){

eSrc.className = “toolbar-button”;

}else if (eType == “click”){

eSrc.className = “toolbar-button”;

window.location.href = eSrc.getAttribute(“href”);

}}

Since you’re now dealing with the DOM event model, you need to add a parameter to the function forthe eventobject Then you use the targetproperty to retrieve the element where the event fired Theremainder of the function remains untouched: You make sure that eSrcis a button and change the ele-ment’s classNameproperty according to the event

Creating Cross-Browser DHTML

By now you’ve written one DHTML script and adapted it to work in both IE and Firefox In this section,you’ll combine the two versions into one cross-browser version You probably already have an idea ofwhat code you’ll change, as you’ve already changed it once However, here you’ll employ a few tricks aswell to ensure that the script works in both browsers

Try It Out The Cross-Browser Toolbar

Open your text editor and type the following:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”

background-color: #E4E2D5;

544

Chapter 13: Dynamic HTML in Modern Browsers

Trang 16

padding: 2px;

}.toolbar span {

padding: 3px;

}.toolbar-button-hover {

border: 1px solid #316AC5;

background-color: #C1D2EE;

padding: 2px;

cursor: pointer;

}.toolbar-icon {

var eType;

var eSrc;

if (window.event){

eType = event.type;

eSrc = event.srcElement;

}else{eType = e.type;

eSrc = e.target;

}

if (eSrc.tagName == “IMG”){

eSrc = eSrc.parentNode;

}

if (eType == “mouseover”){

eSrc.className = “toolbar-button-hover”;

545

Chapter 13: Dynamic HTML in Modern Browsers

Trang 17

}else if (eType == “mouseout”){

eSrc.className = “toolbar-button”;

}else if (eType == “click”){

eSrc.className = “toolbar-button”;

window.location.href = eSrc.getAttribute(“href”);

}}function createToolbar(sName, aButtons){

var toolbar = document.createElement(“div”);

toolbar.id = sName;

toolbar.className = “toolbar”;

for (var i = 0; i < aButtons.length; i++){

var thisButton = aButtons[i];

var button = document.createElement(“span”);

var icon = document.createElement(“img”);

}var myToolbar = new Array();

myToolbar[0] = new Array();

Trang 18

function button_mouseHandler(e){

var eType;

var eSrc;

if (window.event){

eType = event.type;

eSrc = event.srcElement;

}else{eType = e.type;

eSrc = e.target;

}

if (eSrc.tagName == “IMG”){

eSrc = eSrc.parentNode;

}

if (eType == “mouseover”){

eSrc.className = “toolbar-button-hover”;

}else if (eType == “mouseout”){

eSrc.className = “toolbar-button”;

}else if (eType == “click”){

eSrc.className = “toolbar-button”;

window.location.href = eSrc.getAttribute(“href”);

}}This new code uses object detection to assign eTypeand eSrctheir proper values When this process iscomplete, the function behaves as it did in the previous examples

547

Chapter 13: Dynamic HTML in Modern Browsers

Trang 19

This example hasn’t been very large, or overly complex However, the concepts and problems reflect adifficulty DHTML authors face all the time: working with two different event models and using CSSworkarounds to ensure that the DHTML displays correctly in both types of browser If you’re aware ofthis difficulty, dealing with it really isn’t too hard.

Summar y

This chapter has featured quite a few diversions and digressions, but these were necessary to strate the position and importance of the Document Object Model in JavaScript

demon-This chapter covered the following points:

❑ You started by outlining four of the main standards — HTML, ECMAScript, XML, and

XHTML — and examined the relationships among them You saw that a common aim emergingfrom these standards was to provide guidelines for coding HTML web pages Those guidelines

in turn benefited the Document Object Model, making it possible to access and manipulate anyitem on the web page using script if web pages were coded according to these guidelines

❑ You examined the Document Object Model and saw that it offered a browser- and independent means of accessing the items on a web page, and that it resolved some of the prob-lems that dogged older browsers You saw how the DOM represents the HTML document as atree structure and how it is possible for you to navigate through the tree to different elementsand use the properties and methods it exposes in order to access the different parts of the webpage

language-❑ Although sticking to the standards provides the best method for manipulating the contents ofthe web page, none of the main browsers yet implements it in its entirety You looked at themost up-to-date examples and saw how they provided a strong basis for the creation ofdynamic, interoperable web pages because of their support of the DOM

548

Chapter 13: Dynamic HTML in Modern Browsers

Trang 20

Hint: Comment each line as you write it to keep track of where you are in the tree structure, and create a new variable for every element on the page (for example, not just one for each of the TD cells, but nine variables).

Hint: Add any extra code to the end of the script code you have already written.

549

Chapter 13: Dynamic HTML in Modern Browsers

Trang 22

JavaScript and XML

In the previous chapter you took a brief look at Extensible Markup Language (XML) Like HTML,

it consists of elements You saw that its purpose was to describe data rather than to actually play information in any particular format, which is the purpose of HTML There is nothing specialabout XML It is just plain text with the addition of some XML tags enclosed in angle brackets Youcan use any software that can handle plain text to create and edit XML

dis-In this chapter you’ll be covering the fundamentals of XML It’s a huge topic and deserves a wholebook to do it justice, so this’ll be a taster to get you started Before you get down to coding, let’slook at what XML can be used for

What Can XML Do for Me?

Developers like XML for a variety of reasons It makes many web development tasks much pler than they would be with HTML; it also makes possible many tasks that HTML simply cannot

sim-do It is a powerful language with the ability to mold to your specific needs

XML is a data-centric language It not only contains data, but it describes those data by usingsemantic element names The document’s structure also plays a part in the description UnlikeHTML, XML is not a formatting language; in fact, a properly structured XML document is devoid

of any formatting elements This concept is often referred to as the “separation of content andstyle,” and is part of XML’s success, as it makes the language simple and easy to use

For example, you can use XML as a data store like a database In fact, XML is well suited for largeand complex documents because the data are structured; you design the structure and implement

it using your own elements to describe the data enclosed in the element The ability to define the

structure and elements used in an XML document is what makes XML a self-describing language.

That is, the elements describe the data they contain, and the structure describes how data arerelated to each other

Another method in which XML has become useful is in retrieving data from remote servers.Probably the most widely known applications of this method are the RSS and Atom formats for

Trang 23

web syndication These XML documents, and others like them, contain information readily available toanyone Web sites or programs can connect to the remote server, download a copy of the XML docu-ment, and use the information however needed.

A third, and extremely helpful, application of XML, is the ability to transfer data between incompatiblesystems An XML document is a plain text document; therefore, all operating systems can read and write

to XML files The only major requirement is an application that understands the XML language and thedocument structure For example, Microsoft recently released details on Microsoft Office Open XML, thefile format used in Microsoft Office 2007 The files themselves are actually Zip files However, any pro-gram written to read the XML files contained in the Zip file can display the data with no problem; itdoesn’t matter whether they were written under Windows XP, Mac OS X, any flavor of Linux, or anyother operating system

The Basics of XML

The advantage of XML over other document formats is that it specifies a protocol by which a documentcan describe itself For example, a document might describe itself as a particular chapter in a book, con-taining the chapter’s title, the sections, and the text, which is broken into different paragraphs In order

to write XML documents, you need to have a firm grasp on the fundamentals of the language

Understanding XML Syntax

XML is a simple language with simple syntax and rules By following the guidelines in this section,you’ll create XML documents with little trouble

XML Is a Well-Formed Language

Well-formed documents are those that comply with the rules of XML syntax The requirements include,

but are not limited to, the following:

❑ All elements must have an opening and closing tag, or a closing slash in the empty element

❑ Elements must be nested correctly within the root element

It is important to make well-formed XML documents because every XML parser is built according to theXML specification It is an unforgiving language, meaning that any XML parser that follows the stan-dard specification will never display documents that are not well formed

Close the Tags!

The XML specification requires that all elements must have an opening tag and a closing tag This is oneway in which XML is unlike HTML, in which several elements have no closing tag (like <img>and

<br>) So when you open a tag, you need to close it when it contains the data that you want it to

Trang 24

This example shows a simple XML document The first line contains the XML declaration This tells theapplication that is going to use this XML document which version of the specification the documentuses Right now there is only version 1.0 (version 1.1 is coming soon) Note that the line starts with <?and ends with ?> These are the delimiters that indicate there is an XML declaration instruction betweenthem In this case, the instruction tells which version of XML the document uses The declaration alsostates the character encoding used in the document In this case the document conforms to the 1.0 speci-fication of XML and uses the ISO-8859-1 (Latin-1/West European) character set.

XML declarations have no closing tag.

After the declaration, you see a couple of tags enclosing some text The first tag is the opening tag for themyElementelement, and the second is the closing tag for the same element XML is a case-sensitive lan-guage; therefore, make sure the closing tag exactly matches the opening tag

A well-formed element does not need to have any data between the opening and closing tags Take thefollowing line as an example:

<myElement></myElement>

This, too, is a well-formed XML element, even though it contains no data This is referred to as an empty

element In elements such as these, use a shorthand version of closing the tag.

<myElement />

This line of code, as far as an XML parser is concerned, is identical to the previous line of code So whenyou have empty elements, you can use the shorthand way of closing them

There is no rule in XML that states an element must contain data.

Correctly Nest Elements

For years, browser makers have built their Web browsers to render and display pages that are not wellformed Not that it’s a problem, as the Web has grown by leaps and bounds because of the everyman/-woman However, if you loaded these HTML documents into an XML parser, it would throw error aftererror The largest culprit would most likely be incorrectly nested elements

XML requires properly nested elements; they cannot overlap as they can in HTML For example, the lowing XML document is not well formed:

This XML is almost well formed; however, the second <name/>element’s closing tag comes after the

<myDogs/>closing tag This is an example of overlapping elements and will make any XML documentinvalid Close an open element before you close its parent element

If you follow these two rules, you’ll have an easy time when writing XML documents And speaking ofwhich, let’s delve more into XML’s syntax

553

Chapter 14: JavaScript and XML

Trang 25

Document Structure

XML was designed to provide a means of storing data in a structured way All XML documents must

have at least one element The first element in the document is called the root element or the document

ele-ment No matter which name you use, both terms mean the same thing All XML documents must have a

root element, and they cannot have more than one

Think of an operating system’s directory structure Everything begins with the root directory (C:) Thismain directory can have many subdirectories, and those subdirectories can have many more subdirecto-ries, and so on

An XML document is very similar You start with the root element and build the document from there.For example, look at the following XML document:

The first element, <myDogs/>, is the root element of the document From here, two elements called

<name/>are added You could even go farther and add more data (and elements) until you’re satisfiedwith the document There is no limit to the amount of elements you can use in a document; just remem-ber that there can be only one root element, and that the document builds off of that element

XML Elements

XML uses elements to describe the data enclosed in the document So when you create your own XMLdocuments, make sure that the elements properly describe the data enclosed in them Let’s expand uponthe dogs document

The very first line of an XML document contains the XML declaration In this case the document forms to the 1.0 specification of XML and uses the ISO-8859-1 (Latin-1/West European) character set

con-The next line describes the start tag of the root element of the document In this example, it’s saying

“This document contains information on my dogs.”

<myDogs>

554

Chapter 14: JavaScript and XML

Trang 26

The next line opens the <dog/>element, a child of the root element This element contains informationregarding one of the dogs.

<dog breed=”Labrador Retriever”>

Lastly, the <dog/>element contains one child element called name, which holds the name of the dog.The next <dog/>element contains the same type of data:

<dog breed=”Labrador Retriever”>

Trang 27

Obviously, the &lt;entity reference is useful for character data The other entity references can be usedwithin markup where there could be confusion, such as the following:

<statement value = “She said, “Don’t go there!”” />

This line should be written as follows:

<statement value = “She said, &quot;Don&apos;t go there!&quot;” />

Not only will you sometimes want to include elements that you want the XML processor to ignore (that

is, display as character data) in XML documents, but sometimes you will want to put into the documentcharacter data that you want the XML processor to ignore (that is, not display at all) This is where com-ments come in

Note that comments will be displayed when you use the default style sheet This type of text is called

comment text.

556

Chapter 14: JavaScript and XML

Trang 28

XML comments are similar to HTML comments In HTML, comments are specified with the <! and >syntax In XML, comments are created in just the same way! So the following would be a valid XMLcomment:

<! End the names >

Keep a few rules in mind when using comments in XML documents First, never have a hyphen or adouble hyphen (-or ) within the text of the comment; these might be confusing to the XML processor.Second, never place a comment within an opening or closing tag Thus, the following code would bepoorly formed XML:

<name <! The name > >Tom Morello</name>

Likewise, never place a comment inside an entity declaration and never place a comment before theXML declaration

XML declarations must always be the first line in any XML document.

Use comments to comment out groups of elements, if necessary Thus, in the following case, all thenames will be ignored except for Brad Wilk:

<! don’t show these names

<name>Chris Cornell </name>

<name>Tom Morello </name>

Trang 30

The <name/>element contains the dog’s name, and the <age/>element expresses the dog’s age.Because ages typically are counted in months and years, <age/>contains two child elements, <years/>and <months/> Next, the <fullBlood/>element contains one of two Boolean values: yesor no.Naturally, if the dog is a purebreed, the value contained in this element is yes And last, the <color/>element will contain the color of the dog’s coat.

What you have here is a well-formed XML document structure, but let’s take it a step further and seehow you can make it valid

Document Type Definition

If you make a layout mistake in building your XML file, the browser will tell you where things don’tmatch up; it will not inform you if the mistake is related to the actual data We are all human and prone

to mistakes (not often, but they do happen!)

This section introduces a new term: valid XML documents can be well formed or they can be valid, or

they can be both Valid documents are well-formed documents that also conform to a Document TypeDefinition (DTD) A DTD provides the structure for an XML document Look at an e-mail; it has struc-ture The e-mail has a To: field, a Subject: field, and a body There are even optional CC: and BCC: fields.The e-mail program fills in the From: field, and the date and time sent, for us, but they are there Thestructure is so familiar you don’t really notice it, unless it gets messed up in the transmission! This struc-ture makes e-mail easy to read If a program attempts to process this e-mail (which is data, when you getdown to it), it must know the e-mail’s structure in order to parse it Knowing the structure means beingable to parse it correctly each and every time, time after time

DTDs lay out the way an XML file is to be marked up Anyone following this DTD can process an XMLfile from others who have also built their XML files to the same DTD Following a DTD also enables you

to trap errors if a file that is not well formed or that has the wrong data is passed to the application

Enough about what a DTD can do Let’s build one and see

Creating the First DTD File

The purposes of a DTD are as follows:

❑ Declare what the markup is

❑ Declare what the markup means

But how do you build one? There is an entire specification on how to write DTDs This section onlytouches on some of the items that can be used in a DTD

Open any text editor (Notepad in Windows works just fine) and start a new file, name it mydogs.dtd,and follow along Here is what the DTD for the myDogsdocument will look like:

<! The myDogs DTD >

<!ELEMENT myDogs (dog+)>

<! The <dog/> section >

559

Chapter 14: JavaScript and XML

Trang 31

<!ELEMENT dog (name, age, fullBlood, color)>

<!ATTLIST dog breed CDATA #REQUIRED>

<!ELEMENT name (#PCDATA)>

<!ELEMENT age (years, months)>

<! The <age/> section >

<!ELEMENT months (#PCDATA)>

<!ELEMENT years (#PCDATA)>

<! END age section >

<!ELEMENT fullBlood (#PCDATA)>

<!ELEMENT color (#PCDATA)>

<! END <dog/> section >

<! END of myDogs DTD >

The first line, which follows, is a comment Anything between the <! and >will be ignored

<! The myDogs DTD >

It’s always good to comment your code All element declarations follow the following format:

<!ELEMENT elementName (content)>

This declaration is used to declare the elements used in the document To define the root element, usemyDogsas the element name Under myDogsare multiple <dog/>elements, thus the +symbol

<!ELEMENT myDogs (dog+)>

Next is another comment to indicate that what follows is the definition for the <dog/>element

<! The <dog/> section >

If you refer back to the desired XML structure, you’ll see that the <dog/>element has an attribute calledbreedand contains the following elements: name, age, fullBlood, and color

<!ELEMENT dog (name, age, fullBlood, color)>

The commas between each child name and the next indicate that <dog/>has strict ordering If any ment is out of order, the XML document is not valid Because age has sub-elements, they will be definedlater Next, define the breed attribute

ele-<!ATTLIST dog breed CDATA #REQUIRED>

Defining attributes are similar to elements, and follow the following pattern:

<!ATTLIST elementName attributeName attributeType defaultValue>

There are several attribute types, but the most common is CDATA For the default value, #REQUIREDisused to tell the XML parser that the breedattribute must be used in every <dog/>element There arealso other possible default values to use, but #REQUIREDbest fits the document’s needs (After all, youwant to know what type of dog you have, don’t you?)

560

Chapter 14: JavaScript and XML

Trang 32

Use #in #REQUIRED(and in the following code, in #PCDATA) to prevent these words from being preted as element names.

inter-Here is the start of the actual element type definitions These follow the same rules we just went over

<!ELEMENT name (#PCDATA)>

<!ELEMENT age (months, years)>

<! The <age/> section >

<!ELEMENT years (#PCDATA)>

<!ELEMENT months (#PCDATA)>

<! END age section >

<!ELEMENT fullBlood (#PCDATA)>

<!ELEMENT color (#PCDATA)>

<! END <dog/> section >

<! END of myDogs DTD >

That’s it, and this is the simplest way to write the DTD When you write the XML document, you’ll ence this DTD by using the <!DOCTYPE>declaration in the XML document

refer-Bring on the Data

You now have the means to make a well-formed XML document valid Let’s add some actual data to it.The following table shows the data to use:

Data Fields Dog 1 Dog 2 Dog 3

Once again, open any plain-text editor, and create this XML document:

Trang 33

<dog breed=”Labrador Retriever”>

<dog/>elements There is, however, the addition of the DTD file you created earlier

<!DOCTYPE myDogs SYSTEM “myDogs.dtd”>

!DOCTYPEtells the XML parser that you are specifying a document to use as part of this file

Immediately following is myDogs, the name of the root element SYSTEMlets the parser know that thedocument uses external DTD, a DTD found outside of the XML file Finally, “myDogs.dtd”is the loca-tion of the DTD If the DTD were on a web server, the URI would be a path like

http://myserver/myxmlstuff/myfile.dtd If the DTD and the XML file reside in the same folder,only the name of the DTD file needs referencing

If you did not want an external DTD but instead wished to include the DTD within the XML file, this iswhat a portion of it would look like:

<?xml version=”1.0” encoding=”iso-8859-1”?>

<!DOCTYPE myDogs [

<! The myDogs DTD >

<!ELEMENT myDogs (dog+)>

<! The dog section >

<!ELEMENT dog (name, age, fullBlood, color)>

<!ATTLIST dog breed CDATA #REQUIRED>

(rows removed for demonstration)

Trang 34

Either way you go, an XML parser that can validate XML documents will consider this file to be valid.

Go ahead and load mydogs.xmlinto your browser In IE 7, you should see a page like what is shown inFigure 14-1

Trang 35

Firefox cannot validate XML documents IE doesn’t validate documents by default,

but you can download a tool to do so It is called Internet Explorer Tools for

Validating XML and Viewing XSLT Output and can be found at www

Trang 36

Figure 14-3

Here is something else: Look at the XML file in the browser (see Figure 14-1), and you’ll see several reddashes next to some opening tags Clicking these dashes closes the corresponding part of the documenthierarchy You can expand and collapse elements/nodes that have children Therefore, it’s possible tocollapse an entire <dog/>element, or the whole document

The reason you can display this XML file in IE5+ and Firefox and have it be colored and collapsible isthat those browsers have a default style sheet built in for those XML files that don’t reference a stylesheet of their own The use of a style sheet with XML is termed Extensible Stylesheet Language (XSL).(More on this later.)

565

Chapter 14: JavaScript and XML

Trang 37

Figure 14-4

Altering the Look of XML

So far you have defined data and have seen those data displayed in a browser, but will your users likereading raw information? Nope, and this section shows you how to display and format it This sectiondoesn’t teach Cascading Style Sheets (CSS); you saw the basics of CSS in Chapter 12 Instead, it coversonly how to use them with XML

Style Sheets and XML

Using CSS serves several purposes:

❑ It improves the clarity of the document when the document is displayed

❑ You can write once, use often

❑ One change can be reflected in many places

❑ You can present the same data in different ways for different purposes

566

Chapter 14: JavaScript and XML

Trang 38

With a style sheet, all the display rules are kept in one file that is linked to the source document So youneed to define what your display rules will be and associate them with your XML tags.

Create a new file called mydogs.cssand type the following:

dog{margin: 15px;

display: block;

}name{display: block;

font: bold 18pt Arial;

}age{display: block;

color: red;

}fullBlood{

display: none;

}color{display: block;

font-style: italic;

}Here some style rules are defined to match the elements that have data: dog, name, age, fullBlood, andcolor Each one of these defined elements in the XML document contains data to be displayed Just likeyou learned in Chapter 12, element names can be used in CSS to apply a style to that element

What makes a style rule work are the properties, which are between the curly braces ({ }) Action istaken against the matched element Starting with your dogelement there are two properties: marginand display The marginproperty is new It’s basically an edge that surrounds an element If marginis0px, then the edge around the element is zero pixels If it is 15px, then there is a 15-pixel buffer aroundthe element In this case, the marginproperty emphasizes where a dog’s data begins and ends

The remainder of the elements, with the exception of fullBlood, are set to be placed on their own linewith display: block(fullBloodis set to not be shown at all) The nameelement’s text is bolded 18point Arial age’s text is colored red, and the colorelement is italicized

There are now two files: mydogs.xmland mydogs.css, but the XML file needs to reference the CSS file.Open mydogs.xmland add the following line after the XML declaration Save the file as mydogs_css.xml

<?xml-stylesheet href=”mydogs.css” type=”text/css”?>

When you open your XML file in IE, you should see the screen shown in Figure 14-5

567

Chapter 14: JavaScript and XML

Trang 39

Figure 14-5

Figure 14-6 shows how the file looks in Firefox

One thing you may notice is that the data are displayed, yet there’s nothing really to describe whatthey’re about You, of course, know exactly what these data are, because you wrote it CSS can make datalook pretty, but what if you want more? It’s a good thing you asked

Extensible Stylesheet Language

The following sections show you how to use XSL to format XML documents using XSLT transformations

What Is an XSLT Transformation?

XSLT is a template-based programming language that enables you to restructure your content to createthe look you require XSLT transformations can allow different kinds of software applications to

exchange data They can also be used to generate multiple views of the same source document to enable

a web site’s content to be displayed on myriad devices

568

Chapter 14: JavaScript and XML

Ngày đăng: 09/08/2014, 14:21

TỪ KHÓA LIÊN QUAN