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

THE BOOK OF JAVASCRIPT, 2ND EDITION phần 9 ppsx

55 346 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 đề The Book of JavaScript, 2nd Edition phần 9 ppsx
Chuyên ngành Computer Science
Định dạng
Số trang 55
Dung lượng 352,09 KB

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

Nội dung

Chapter 3In this assignment, you are asked to send people you like to one page, people you don’t like to another page, and everyone else to a third page.. Chapter 10This assignment asks

Trang 2

A N S W E R S T O A S S I G N M E N T S

Here are solutions to the assignments I’ve given at the end of each chapter The scripts and images used in the solutions may be found

on this book’s companion website (http://www bookofjavascript.com) The JavaScript in this appendix contains comments where I think explanation is neces- sary If your solution works and is not much longer than mine, you’ve done a good job There is no assignment for Chapter 1, so we’ll start with Chapter 2.

Trang 3

<head>

<title>Chapter 2 Assignment</title>

<script type = "text/javascript">

<! hide me from older browsers// get the date information//

var today = new Date();

var the_day = today.getDate();

var the_month = today.getMonth();

var the_hour = today.getHours();

var the_minutes = today.getMinutes();

var the_seconds = today.getSeconds();

// correct for the month starting from zero//

var the_whole_date = the_month + "/" + the_day + " ";

var the_whole_time = the_hour + ":" + the_minutes + ":" + the_seconds;// This is the time fixer function don't worry about how this works either.function fixTime(number) {

if (number < 10) { number = "0" + number;

} return number;

}// show me >

</script>

</head>

<body>

Right now it's:

<script type = "text/javascript">

<! hide me from older browsers// write the date

Trang 4

Chapter 3

In this assignment, you are asked to send people you like to one page, people you don’t like to another page, and everyone else to a third page This should exercise your new understanding of if-then-else-if statements.

<html><head><title>Chapter 3 Assignment</title></head>

<body>

<script type = "text/javascript">

<! hide me from older browsers

// get the visitor's name

//

var the_name = prompt("What's your name?", "");

// If the name is thau, dave, pugsly, or gomez,

// send the visitor to Sesame Street

// If it's darth vader, the evil emperor, or jar jar binks,

// send the visitor to the American Psychological Association

// for some therapy

// If it's none of the above, send him or her to the New York Times

if ((the_name == "thau") || (the_name == "dave") ||

(the_name == "pugsly") || (the_name=="gomez"))

Trang 5

<script type = "text/javascript">

<! hide me from older browsers// open the little window with the page image_page.html and call the// little window the_window

//

var the_window = window.open("image_page.html","the_window","width=100,height=100");// show me >

Trang 6

<img name = "the_image" src = "happy.gif">

<html><head><title>Chapter 6 Assignment</title>

<script type = "text/javascript">

<! hide me from older browsers

// function fancySwap() takes three parameters:

// 1 the web page image that's getting swapped out

// 2 the filename of an image to swap into the web page image

// 3 a URL to open into a new window

<img src = "normal_sun.gif" name = "sun" border = "0">

Trang 7

the correct time should appear in the text field When you click on the update button, the clock should update with the time from the zone you’ve selected with the radio buttons.

This solution has two main functions: updateClock() is called when the update button is clicked, and updateReadout() is called when one of the time zone radio buttons is clicked.

<html><head><title>Chapter 7 Assignment</title>

<script type = "text/javascript">

<! hide me from older browsers// Function updateReadout() takes one parameter, the time zone to// convert the time to The parameter can be either newyork, sanfran or // tokyo

// The function determines the time for that time zone and then sets the // value of a text field to that time

function updateReadout(the_zone){

// get the current UTC time //

var now = new Date();

var the_hours = now.getUTCHours();

var the_minutes = now.getUTCMinutes();

var the_seconds = now.getUTCSeconds();

// adjust for selected time zone //

if (the_zone == "newyork") {

if (the_hours < 0) {

the_hours = the_hours + 24;

} else if (the_hours > 24) { the_hours = the_hours - 24;

} // put zeros in front of minutes and seconds if necessary the_minutes = formatTime(the_minutes);

Trang 8

// function formatTime() takes a number as a parameter.

// If that number is less than 10, it puts a 0 in front

// of it for formatting purposes

// By looping through a set of radio buttons, function updateClock()

// checks to see which time zone has been selected by the viewer Once // it determines the selected time zone, it calls updateReadout()

<form name = "clock_form">

<input type = "text" name = "readout">

<input type = "button" value = "update" onClick = "updateClock();"><br>San Francisco <input type = "radio" name = "zones" value = "sanfran"

onClick = "updateReadout('sanfran');" checked><br>

New York <input type = "radio" name = "zones" value = "newyork"

Trang 9

<html><head><title>Chapter 8 Assignment</title>

<script type = "text/javascript">

<! hide me from older browsers// function getNumbers() gets a number of bars to draw// and the length of those bars It calls the drawSquares()// function to actually draw the bars to the web page

//

function getNumbers(){

// create a new array //

var the_values = new Array();

// find out how many bars the person wants //

var how_many = prompt("How many bars?","");

// now loop that many times, asking for a value // each time and loading that value into the array //

for (var loop = 0; loop < how_many; loop++) {

var value = prompt("How long is this bar? (1-10)","");

the_values[loop] = value;

} // now loop through the array and print out the bars //

for (var loop = 0; loop < how_many; loop++) {

drawSquares(the_values[loop]);

}}// function drawSquares()// takes a number of squares to draw, and then draws them to // the web page

//

function drawSquares(the_number){

for (var loop = 0; loop < the_number; loop++) {

window.document.write("<img src='square.gif'>");

} window.document.write("<br>");

}// show me >

Trang 10

<head>

<title>Chapter 9 Assignment</title>

<script type = "text/javascript">

<! hide me from older browsers

// preload the images

var the_images = new Array();

the_images[0] = new Image();

// function rotateImage() swaps in the next image in the_images

// array and increases the index by 1 If the index exceeds the

// number of images in the array, index is set back to zero

// setTimeout is used to call the function again in one second

<input type = "button" value = "Start the show"

onClick = "clearTimeout(the_timeout); rotateImage();">

<input type = "button" value = "Stop the show"

onClick = "clearTimeout(the_timeout);">

</form>

</body>

</html>

Trang 11

Chapter 10

This assignment asks you to create a page with at least two frames The first frame should contain a submit button and a text box into which a visitor should type a URL After the submit button is clicked, the second frame shows the web page called by the URL in the text box In addition to providing a

location box, the browser page in the solution uses Salon’s image map to

show various URLs in the display frame.

Because it uses frames, this assignment requires three HTML files: index.html, assignment-nav.html, and blank.html

index.html

The first page, index.html, lays out the frameset.

<html><head><title>Chapter 10 Assignment</title></head>

<frameset rows = "50%,*">

<frame src = "assignment-nav.html" name = "nav">

<frame src = "blank.html" name = "contents">

click on an area of the map

<form onSubmit = "parent.contents.location=this.the_url.value; return false;">

<input type = "text" name = "the_url">

<MAP name = "left">

<AREA coords = "9,23,41,42" shape = "RECT" href = "#"

Trang 12

<AREA coords = "26,42,75,64" shape = "RECT" href = "#"

This assignment extends Chapter 10’s assignment by adding string validation

to make sure the URLs entered in the browser’s location bar are valid web

addresses This means the URL should start with http:// or https://, have no

spaces, and have at least two words with a period between them.

The solution begins with the code from Chapter 10’s assignment and adds a function named domainCheckAndGo() that performs the string validation Like the Chapter 10 assignment, this assignment requires three HTML files because it uses frames.

index.html

The first page, index.html, lays out the frameset.

<html><head><title>Chapter 11 Assignment</title></head>

<frameset rows = "50%,*">

<frame src = "assignment-nav.html" name = "nav">

<frame src = "blank.html" name = "contents">

</frameset>

</html>

Trang 13

The second page, assignment-nav.html, contains the contents of the top frame, including the JavaScript.

<html><head><title>nav</title>

<script type = "text/javascript">

<! hide me from older browsers// function domainCheckAndGo()// This function makes sure a URL is legal If it is, it // sends the visitor to that URL

function domainCheckAndGo(the_url){

// split the URL into two parts, along the //

// there should be two parts to it, the protocol (for example, http:) // and the address

var first_split = the_url.split('//');

if (first_split.length != 2) {

alert("Sorry, there must be one // in a domain name");

return false;

} // Now check to see if the URL is legal see the alerts in the // if-then statement to see what the if-then statement is checking

// If any of the conditions are violated, the script calls up an // alert box explaining the error and then uses return to exit // the function without changing the URL in the bottom frame

if ((first_split[0] != 'http:') && (first_split[0] != 'https:')) {

alert("Sorry, the domain must start with http:// or https://");

return false;

}

if (the_url.indexOf(' ') != -1) {

alert("Sorry, domains can't have spaces");

return false;

} // get everything after the http://

//

var two_slashes = the_url.indexOf('//');

var all_but_lead = the_url.substring(two_slashes + 2, the_url.length); var domain_parts = all_but_lead.split('.');

if (domain_parts.length < 2) {

alert("Sorry, there must be at least two parts to a domain name");

return false;

} // Loop through all the parts of the domain, making // sure there's actually something there for example, // http://i.am.happy com is not legal because there // are three dots in a row

Trang 14

for (var loop = 0; loop < domain_parts.length; loop++)

// If we've made it this far, the URL must be legal,

// so load the URL into the frame

click on an area of the map

<form onSubmit = "domainCheckAndGo(this.the_url.value); return false;">

<input type = "text" name = "the_url">

<MAP name = "left">

<AREA coords = "9,23,41,42" shape = "RECT" href = "#"

Trang 15

<script type = "text/javascript">

<! hide me from older browsers// this is from the webmonkey cookie library at http://www.webmonkey.com///

function WM_readCookie(name) { if(document.cookie == '') { // there's no cookie, so go no further return false;

} else { // there is a cookie var firstChar, lastChar;

var theBigCookie = document.cookie;

lastChar = theBigCookie.indexOf(';', firstChar); //

if(lastChar == -1) lastChar = theBigCookie.length;

return unescape(theBigCookie.substring(firstChar, lastChar));

} else { // If there was no cookie of that name, return false

return false;

} } }

// WM_readCookie// Function setCookie() sets a cookie named was_here to expire far// in the future

//

function setCookie(){

var the_future = new Date("December 31, 2023");

var the_cookie_date = the_future.toGMTString();

var the_cookie = "was_here=yes;expires=" + the_cookie_date;

document.cookie = the_cookie;

Trang 16

// Function checkFirst() checks if the was_here cookie

// has been set If it hasn't, the alert pops up and the

// cookie is set using setCookie();

<script type = "text/javascript">

<! hide me from older browsers

value calls for a number to be added to the current position If the variable is

x_motion, adding a value will move the smiley face to the right If the variable

isy_motion, adding a value will move the smiley face down

<html>

<head>

<title>Chapter 13 Assignment</title>

<script type = "text/javascript">

<! hide me from older browsers

// set the direction

//

var x_motion = "plus";

var y_motion = "plus";

// set the borders

Trang 17

// This function moves the face 5 pixels in the vertical dimension// and 5 pixels in the horizontal dimension It uses two variables,// x_motion and y_motion, to determine the direction left versus// right and up versus down When the face reaches a horizontal or// vertical border, the x_motion or y_motion variable changes, so that// the next time the face moves, it moves in the opposite direction function moveSmile()

{ var the_smile = document.getElementById("smile").style;

if (x_motion == "plus") {

the_smile.left = parseInt(the_smile.left) + 5;

} else { the_smile.left = parseInt(the_smile.left) - 5;

}

if (y_motion == "plus") {

the_smile.top = parseInt(the_smile.top) + 5;

} else { the_smile.top = parseInt(the_smile.top) - 5;

}

if (parseInt(the_smile.left) > right_border) {

y_motion = "minus";

} else if (parseInt(the_smile.top) < top_border) { y_motion = "plus";

} theTimeOut = setTimeout('moveSmile()', 100);

}// show me >

<div id = "smile" style = "position:absolute; left:100; top:100;">

<img src = "happy_face.gif" width = "130" height = "75">

</div>

</body>

</html>

Trang 18

The second file is the HTML page that contains the JavaScript and Ajax calls

to read in and display the file.

<html><head><title>Chapter 14 Assignment</title>

<script type="text/javascript">

<! hide me from older browsers

// gets the names from addressBook.xml and puts them into the select boxfunction populatePullDown() {

Trang 19

} } writeSelect(name_array);

} } } request.send(null);

}// takes an array and writes the contents to theSelectfunction writeSelect(the_array) {

var this_option;

var this_select = document.getElementById("theSelect");

for (var loop = 0; loop < the_array.length; loop++) { this_option = new Option();

this_option.value = the_array[loop];

this_option.text = the_array[loop];

this_select.options[loop] = this_option;

}}// takes a name, gets the information about that person from // addressBook.xml and writes it to the correct divs

function loadInfo(the_name) {

if (window.XMLHttpRequest) { request = new XMLHttpRequest();

} else if (window.ActiveXObject) { request = new ActiveXObject("Microsoft.XMLHTTP");

}

if (request) { request.open("GET", "addressBook.xml");

request.onreadystatechange = function() {

if (request.readyState == 4) { xml_response = request.responseXML;

elements = xml_response.getElementsByTagName("name");

for (var loop = 0; loop < elements.length; loop++) {

if ((elements[loop].firstChild != null) &&

(elements[loop].firstChild.nodeValue == the_name)) { parent = elements[loop].parentNode;

} else if (children[inner].nodeName == "phone") { phone_node = children[inner];

} else if (children[inner].nodeName == "email") { email_node = children[inner];

} } insertValue(document.getElementById("theName"), elements[loop]);

insertValue(document.getElementById("theAddress"), address_node);

insertValue(document.getElementById("thePhone"), phone_node); insertValue(document.getElementById("theEmail"), email_node);

Trang 20

<b>Name:</b> <span id = "theName"></span><br>

<b>Address:</b> <span id = "theAddress"></span><br>

<b>Phone:</b> <span id = "thePhone"></span><br>

<b>Email:</b> <span id = "theEmail"></span><br>

</body>

</html>

Chapter 17

This is your final exam If you got this working, take yourself out to dinner

If you gave it a good shot, take yourself out to dinner Heck, if you’ve read to this point in the book, take yourself out to dinner.

The assignment was to add these critical features to the To Do list cation described in the chapter:

appli-z Allow new users to join the service

z Allow a user to permit another user to access his or her To Do list Only the HTML file containing the JavaScript needs to be changed here First, you needed to make a change to the HTML at the bottom of the page

to add the “join” link to the login section:

<h2>Login Section</h2>

<div id = "loginArea">

<a href = "#" onClick = "displayLogin(); return false;">login</a> or

<a href = "#" onClick = "displayJoin(); return false;">join</a>

</div>

Then there are a number of new functions First, I’ll cover the functions necessary to provide the ability to join, then the functions necessary to allow someone to give another user access to his or her list.

Trang 21

Join Functions

Seven functions work together to create a new user:

displayJoin() Displays the form that will collect new user information

doJoin() Called when the join link is clicked; reads in userInfo.xml and calls processJoin()

processJoin() Creates a new user and adds it to userInfo.xml

createUserFileAndLogin() Creates an empty To Do list for a new user

addUser() Actually creates a new userInfo.xml file

makeNewUser() Makes a new user element

makeUserInfoDoc() Converts the userInfo.xml file into a string to save

"<input type='button' value='submit' " + "onClick='doJoin(this.form);'></form>";

document.getElementById("loginArea").innerHTML = theForm;

}// reads in the userInfo.xml file and calls processJoinfunction doJoin(my_form) {

readFileDoFunction("userInfo.xml", "GET", function() {

if (request.readyState == 4) {

if (request.status == 200) { processJoin(request.responseXML, my_form);

} else { document.getElementById("errorDiv").innerHTML = "Sorry, there was a problem with the server.";

} } } );

}// creates a new user and adds it to the userInfo.xml filefunction processJoin(user_info, my_form) {

var user_name = my_form.elements["name"].value;

var user_password = my_form.elements["password"].value;

var user_password_2 = my_form.elements["password2"].value;

var profile = my_form.elements["profile"].value;

var error = "no error";

var this_user = getUser(user_info, user_name);

if (this_user != null) { error = "A user with this name already exists.";

} else if (user_password != user_password_2) { error = "The two provided passwords don't match.";

}

if (error == "no error") { var new_user_doc = addUser(user_name, user_password, profile, user_info);

Trang 22

saveFileDoFunction("userInfo.xml", new_user_doc,

function() {

if (request.readyState == 4) {

if ((request.responseText == "success")&&(request.status == 200)) { createUserFileAndLogin(user_name);

var the_file = "<?xml version='1.0'?><list>" +

"<name>" + the_user + "</name>" +

// creates a new userInfo.xml document with the new user

function addUser(the_name, the_password, profile, user_info) {

var users_array = user_info.getElementsByTagName("user");

var new_users_array = new Array();

for (var loop = 0; loop < users_array.length; loop++) {

// makes a new user element

function makeNewUser(the_name, the_password, profile, list_array) {

var new_user = document.createElement("user");

var new_name = document.createElement("name");

new_name.appendChild(document.createTextNode(the_name));

var new_password = document.createElement("password");

Trang 23

var the_doc = "<?xml version='1.0' ?>";

the_doc += "<profile>" + getFirstValue(this_user, "profile") + "</profile>";

the_doc += "<lists>";

this_lists = this_user.getElementsByTagName("lists")[0];

var these_lists = this_lists.getElementsByTagName("list");

for (var list_loop = 0; list_loop < these_lists.length; list_loop++) { the_doc += "<list>" + these_lists[list_loop].firstChild.nodeValue + "</list>";

} the_doc += "</lists>";

the_doc += "</user>";

} the_doc += "</users>";

return the_doc;

}

Giving a User Access to Your To Do List

These seven functions allow a user to share his or her To Do list with another

user I’ll use the word owner to refer to the user who owns the To Do list, and the word collaborator to refer to the user being given access to the owner’s

To Do list.

displayHomeInformation() Just like the one in Chapter 16, but adds an additional link that calls giveAccess()

giveAccess() Reads in all the system’s users and calls listAllUsers()

listAllUsers() Creates a form with a radio button for each potential collaborator, so one may be chosen

Trang 24

readyAddAvailableUser() Reads in the userInfo.xml list and calls

addAvailableUser()

addAvailableUser() Adds the newly chosen collaborator to the owner’s

lists section in the userInfo.xml file

addNewAvailableToUserElement() Returns a new user element with the laborator’s name added to the owner’s lists element

col-// add a "Give another user access" link to the loginArea after a person has // logged in by changing displayHomeInformation()

// create the form showing all the users

function listAllUsers(user_info, current_user) {

var display = "<form>";

var all_users = user_info.getElementsByTagName("user");

}

display += "</form>";

document.getElementById("contentArea").innerHTML = display;

}

// get userInfo.xml and add a new available user

function readyAddAvailableUser(user_to_add, this_user) {

readFileDoFunction("userInfo.xml", "GET",

function() {

if (request.readyState == 4) {

if (request.status == 200) {

Trang 25

addAvailableUser(request.responseXML, user_to_add, this_user); } else {

document.getElementById("errorDiv").innerHTML = "Sorry, there was a problem getting the list of users.";

} } } );

}// add the new user to the user's available list, then // create a new userInfo.xml document and save itfunction addAvailableUser(user_info, user_to_add, current_user) { var new_user_array = new Array();

var curr_user_array = user_info.getElementsByTagName("user");

add_to_array = this_user;

} new_user_array[loop] = add_to_array;

} var new_user_doc = makeUserInfoDoc(new_user_array);

saveFileDoFunction("userInfo.xml", new_user_doc, function() {

if (request.readyState == 4) {

if ((request.responseText == "success")&&(request.status == 200)) { document.getElementById("contentArea").innerHTML = "";

displayLegalLists(current_user);

} else { document.getElementById("errorDiv").innerHTML = "Sorry, there was an error saving the user information "; }

} } );

}// return a new user element with the new user added to the available listfunction addNewAvailableToUserElement(this_user, user_to_add) {

var lists = this_user.getElementsByTagName("lists")[0];

var the_name = getFirstValue(this_user, "name");

var profile = getFirstValue(this_user, "profile");

var the_password = getFirstValue(this_user,"password");

var lists_array = lists.getElementsByTagName("list");

var new_lists_array = new Array();

for (var loop = 0; loop < lists_array.length; loop++) { new_lists_array[loop] = lists_array[loop].firstChild.nodeValue;

} new_lists_array[loop] = user_to_add;

var new_user = makeNewUser(the_name, the_password, profile, new_lists_array);

return new_user;

}

Trang 26

R E S O U R C E S

You are not alone There are plenty of JavaScript and Ajax resources to guide and support you along the path to JavaScript mastery This book is just the beginning of your journey In this appendix you’ll find tutorials, libraries, frameworks, and blogs that will give you more informa- tion than you could possibly process.

Tutorials

This book covered all of the basics of JavaScript and Ajax, and many advanced topics as well Here are tutorials that will help you fill in the details not covered in this book.

Trang 27

Cascading Style Sheets Tutorials

Cascading Style Sheets (CSS) and the JavaScript style object were used throughout the book to add formatting to HTML elements CSS is a big topic all on its own.

Webmonkey http://www.webmonkey.com/webmonkey/authoring/ stylesheets

W3 Schools http://www.w3schools.com/css/default.asp

Westciv http://www.westciv.com/style_master/academy/css_tutorial

Advanced Topics in JavaScript

There aren’t many aspects of JavaScript not covered in this book You might want to learn even more about object-oriented programming in JavaScript, how events work in different browsers, and handling errors.

Object-Oriented Programming

Object-oriented programming (OOP) is a programming style that simplifies

many aspects of programming The following tutorials at WebReference.com describe OOP in detail and discuss how to use this style of coding with JavaScript:

http://www.webreference.com/js/column79 http://www.webreference.com/js/column80

Advanced Event Handling

Chapters 2 and 13 covered many details about how to handle events in JavaScript Believe it or not, there is a bit more to learn on the topic A series

of articles at the bottom of this QuirksMode.org page give an excellent depth discussion of advanced event handling:

Ngày đăng: 06/08/2014, 16:23

TỪ KHÓA LIÊN QUAN