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

Tutorial 10 programming with javascript(2)

51 689 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

mpl2txt.htm mplstyles.css random.js + 11 graphic files ads.js fronttxt.htm random.js styles.css + graphic files datetime.js skymaptxt.htm skyweb.css + 26 graphic files back.jpg functi0ns.j~ functi0ns.j~ log0.j ~g sunday.htm - saturday.htm todaytxt.htm + style sheets I I HTML 564 HTML and XHTML Tutorial 10 Programming with JavaScript I Session 10.1 Introducing JavaScript You meet with Kate to discuss her goals regarding the e-mail addresses on the libraw! staff directory page She shows you the content and page layout she has created To open the staff directory page: Use your text editor to open mpltxt.htm from the tutorial.lO\tutorial folder included with your Data Files Enter your name and the d a t e in the comment' section at the top of the file and save the file as mpl.htm in the same folder ) Take some time to scroll through the document to become familiar with i t s ( tents and structure ) Open mpl.htm in your Web browser Figure 10-1 shows the initial appearance ( the Web page Note that the staff directory table contains a column in which Kate wants to ins links to each employee's e-mail address; right now the column is empty I Monroe Public Library Staff page Figure 10-1 1-1 Ha ~aoe Staff Directory Although the staff directory page has proven invaluable in making library emplo more responsive to the needs of the public, Kate is concerned about the security risks oj putting e-mail addresses in that directory Kate is most concerned about sparn Spam is essentially junk e-mail-messages that advertise products and services not requested by the recipient A spammer is a person who sends these unsolicited e-mails, sometimes in bulk e-mailings involving tens of thousands of recipients Aside from the annoyance of receiving unsolicited e-mail, spam costs companies thousands-and sometimes millions of dollars each year by consuming valuable resources on mail servers and other devices forced to process the messages Spam also reduces productivity by forcing employees to wade through numerous spam messages every day to find messages that are truly relevant I I rutorial 10 Programming with JavaScript HTML and XHT! One way that spammers collect e-mail addresses is through the use of e-mail harvesters An e-mail harvester is a program that scans documents, usually Web pages, looking for e-mail addresses Any e-mail address the harvester finds within the document code is added to a database, which can then be used for sending spam So by putting the staff's e-mail addresses in the HTML code for the staff directory, Kate is also making them available to e-mail harvesters See Figure 10-2 Harvesting e-mail addresses I , I F - I I I ~ I(IUUI I F J J F J I,, the staff directory I Kate would like you to scramble the e-mail addresses so that they don't appear within the Web page code; but when a browser loads and renders the page for a user, the e-mail addresses are unscrambled See Figure 10-3 This mechanism will thwart most e-mail harvesters examining the document's HTML code while making the addresses available to users viewing the page on the Web Note that some e-mail harvesters can still view both the underlying code and the page as they are rendered by a browser, so the proposed scrambling method is not 100% effective However, because this technique will thwart many e-mail harvesters, Kate accepts it as a compromise solution Scrambling e-mail addresses e-mail address scrambled with JavaScript, keeping it from appearing in the page code the browser runs a JavaScriptprogram to unscramble the e-mail address that the end user can view Figure 10-3 I I HTML 5CC HTML and XHTML Tutorial 10 Programming with lavascript Neither HTML nor XHTML has features that allow you to scramble and unscramble the e-mail addresses from Kate's staff directory This is not a standard function of Web browsers either Therefore, you'll have to write a program to this Kate doesn't want library patrons to have to download any special applications; she wants the scrambling and unscrambling to appear behind the scenes of the library Web page After some discussion, you decide that JavaScript is well suited to this task You'll start on this project by first finding out just what JavaScriptis and how to use it Server-Side and Client-Side Programming Programming on the Web comes in two types: server-side programming and client-side programming In server-side programming, a program is placed on the server that hosts a Web site The program is then used to modify the contents and structure of Web pages In some cases, users can interact with the program, requesting that specific information be displayed on a page, but the interaction is done remotely from the user to the server See Figure 10-4 3) a server-side program processes the information and may send additional feedback to the user C* r % L 1) user retrieves Web page from the server t J 2) program information running is sent on the to aserver There are advantages and disadvantages to this approach A program running on a server can be connected to a database containing information not usually accessible to end users, enabling them to perform tasks not available on the client side This enables Web pages to support such features as online banking, credit card transactions, and discussion groups However, server-side programs use Web server resources, and in some cases a server's system administrator might place limitations on access to server-side pr grams to prevent users from continually accessing the server and poten~iallyoverloadin / I Tutorial 10 Programming with lavascript HTML and XHTM HTML !Mi7 : Figure 10-5 I lllM NH HTML and XHTML Tutorial 10 Programming with JavaScri-' Figure 10-6 4) a server-side program processes the data from the client-side program 3) information is sent from the program to the server ) user runs a program locally In this tutorial you'll work only with client-side programming However, it's important to be aware that in many cases, a complete Web program includes both cli.ent-side and sewer-side elements The Development of JavaScript Several programming languages can be run on the client side One client-side programming language that you worked with in Tutorial is Java When Java was introduced, its I advantages were quickly apparent and it was soon in wide use in many different browsers However, creating a Java applet required access to the Java Development Kit UDK), so nonprogrammers found it difficult to write their own Java applets To simplify this process, a team of developers from Netscape and Sun Microsystems created a subset of Java called JavaScript, which was different from Java in several important ways Java is a compiled language, meaning that the program code must be submitted to a compiler that manipulates it, translating the code into a more basic language that machines can understand For Java, this compiled code is the Java applet Therefore, to create and run a program written in a compiled language, you need both the compiler and an application or operating system that can run the compiled code On the other hand, JavaScripti s an interpreted language, meaning that the program code is executed directly without compiling You need only two things to use JavaScript: 1) a text editor to write the JavaScriptcommands, and 2) a Web browser to run the commands and display the results This means that JavaScriptcode can be inserted directly into an HTML or XHTML file, or placed in a separate text file that is linked to the Web page JavaScript i s not as powerful a computing language as Java, but it is simpler to us and meets the needs of most users who want to create programmable Web pages Figu 10-7 highlights some of the key differences between Java and JavaScript I II ' compil - anguage + I Tutorial 10 Programming with JavaScript HTML and XHTML Comparing Javaand JavaScript h interpreted language Requires the JDK (Java Development Kit) to create the applet Requires a text editor Requires a JZrmvirtuai machine or interpreter to run the apple& Requires a browser that can interpret JavaScript code Applet files are distinct from the HTML and JavaScript m r -a m s are inteqrated with HTML and XHTML code XHML code Source code i; hydd- * , ; L - Powerful, requiring programming knowtedge Source code is accessible to the user Simpler, requiring less programming know~eugeana Through the years, JavaScripthas undergone several revisions lnternet Explorer actually supports a slightly different version of JavaScript called JScript.Although JScript is almost identical to JavaScript, some JavaScript commands are not supported in JScript, and vice versa In addition, although it is tempting to use commands available in the latest JavaScriptor JScript versions, these commands might prevent your programs from running on older browsers For these reasons, you should always test your JavaScript programs on a variety of Web browsers Because of the proliferation of competing versions and revisions of scripting languages, the responsibility for developing a scripting standard has been transferred to an international body called the European Computer Manufacturers Association (ECMA) The standard developed by the ECMA is called ECMAScript-though browsers still refer to it as JavaScript.Other client-side programming languages are also available to Web page designers, such as the lnternet Explorer scripting language VBScript However, because of the nearly universal support for JavaScript, you'll use this language for your work on the library Web site Working with the Script Element JavaScriptprograms can be placed directly in an HTML file or they can be saved in an external text file Placing JavaScriptcode in a Web page file means that users only need to retrieve one file from the server In addition, because the code and the page it affects are both within the same file, it can be easier to locate and fix programming errors However, if you place the code in a separate file, the programs you write can be shared by the different pages on your Web site In this tutorial, you'll work with JavaScriptcode entered into an HTML file as well as code stored in an external file You'll first examine how to insert JavaScriptcode directly into an HTML file ~reatinga Script Element script type="rnirne-typett> s c r i p t commands HTML 570 HTML and XHTML Tutorial 10 Programming with JavaScript where mime-type defines the language in which the script is written and script commands are commands written in the scripting language l e type attribute is required for XHTML documents and should be used for HTML documents as well The MlME type for JavaScript programs is textljavascript; meaning that for JavaScriptprograms, you would use the following form: - - , I* JavaScript commands + You might see other ways of entering script elements into Web page code In earlier versions of HTML, the language attribute was used in place of the type attribute to indicate the script language For older browsers, you indicate that the scripting language is JavaScript using the following form: cscript lang~age=~JavaScript"s JavaScript commands The language attribute has been deprecated and is not supported by strict applications of XHTML, so you should use the type attribute in its place if you want to conform with current standards Note that the script element can be used with programming languages other than JavaScript.Other client-side scripting languages are identified by using a different value for the type attribute For example, if you use VBScript from Microsoft, the MlME type is textlvbscript You won't useVBScript in this tutorial I Reference Window I Creating a Script Element To place a JavaScript script element into the Web page, insert the two-sided tag cscript type=qtmime-typet'z script commands where mime-type defines the language in which the script is written and script commands are commands written in the scripting language For JavaScript programs, set the mime-type to textljavascript I Placing the Script Element When a browser encounters a script element within a file, it treats any lines within the element as commands to be run Script elements are processed in the order in which they appear within an HTML file; there is no limit to the number of script elements that you can use within a Web page Scripts can be placed in either the head section or the body section of a document When placed in the body section, a browser interprets and runs them as it loads the different elements of the Web page Although a single page can contain many script elements, the browser still can work with them as a single unit So JavaScript commands that are created in one script element can be referenced by commands in other script elements I , I Tutorial 10 Programming with JavaScript HTML and XHTML Writing a JavaScript Statement NOW that you've rwiewed some of the basics involved in entering JavaScript into your HTML files, you'll examine how to enter JavaScript code Every JavaScript program consists of a series of statements Each statement-also known as a command-is a single line that indicates an action for the browser to take A statement should end in a sernicxrIan, employing the syntax JavaScript statement; where EavaScript statement is the code that the browser runs The semicolon is the official way of notifying the browser that it has reached the end of the statement Most browsers are very forgiving and still interpret most statements correctly even if you neglect to include the ending semicolon However, i t is good programming practice to include the semicolons and some browsers require them JavaSeript and X M L Parser Using JavaScript code within an XHTML file can lead to problems because XHTML parsers attempt to process the symbols in JavaScript code Because character symbols such as angle brackets (o) and the ampersand (&) are often used in JavaScript programs, this can lead to a page being rejected by an XHTML parser To avoid this problem, you can place your JavaScript code within a CDATA section as follows: e=Mtext/javascriptll> JavaScript code where lavascript code is the code contained in the JavaScript program The CDATA section marks the text of the JavaScript code as data that should not be processed by XHTML ately, the CDATA section is not well supported by current browsers is not to embed your scripts within XHTML files at all, but instead to rnal files This practice has the added advantage of separating program from page content I f you need to create valid XHTML documents, this is probably the Writing Output to a Web pocument1 e iirst JavaScriptprogram you add to Kate's document is a program that writes the text t,an e-mail address into the Web page Although you could enter the e-mail address directly, you use this opportunity to experiment with JavaScript.You also build on this t as you progress through the rest of the tutorial You insert the e-mail for Catherine Adler as the first entry in the staff directory Her e-mail address is mpl.gov To write this text to the Web document, you insert the following ipt type="text/javascriptv> ocument write (llcadler@mpl gov") ; ite0 statement tells the browser to send the text string cadler@mpl.gov the Web page document To see how your browser applies this command, enter the ript element and command into Kate's mpl.htm file I H m m HTML 572 I IML and XHTML Tutorial 10 Programming with JavaScrip To write text to the Web page using Javaacr : Return t o the mpl.htm in your text editor ) I Locate the table cell after the entry for Catherine Adler and insert the following code, as shown in Figure 10-8: cscript type=ntext/javascript"> docwnent.write(ncadler@mpl.govn); a =i script to write conten Save your changes to the file and then reload mpl.htm in your Web browser As shown in Figure 10-9, the text of Catherine's e-mail address should appear in the staff directory Figure 10-9 Text generated by JavaScript l~tafD f irector) e-mail address inserte using JavaScript -ti ;j :.q Trouble? Internet Explorer might display a yellow alert bar at the top of the - .i' " browser window with a warning that it has restricted access to active content for security reasons This is done to enable users to prevent their browsers from run- ning unwanted scripts To run the script, click the information bar and choose Allow Blocked Content from the pop-up menu, and then click Yes in the dialog box that follows Note that the placement of the script element tells the browser where to place the new text Because the script element is placed between the opening and closing tags, the text generated by the script is placed there as well In more advanced JavaScript programs, you can direct your output to specific locations in the Web page document-but that's beyond the scope of this tutorial .:,f I I HTMI UI L M L and XHTML Tutorial 10 Programming with lavdxript I I! I Figure 10-30 I Browsers also offer various tools for debugging JavaScriptprograms Microsoft offers the Microsoft Script Debugger, a debugger available for use with its Internet Explorer browser running under Windows XP The Microsoft Script Debugger is available for free from the Microsoft Web site and is also included with the Microsoft Office XP suite When the Microsoft Script Debugger is installed on your system, it displays a prompt when it encounters a load-time or run-time error in one of your scripts See Figure 10-31 Figure 10-31 I A RmbneR m has d Tip To enable script debugging on Internet Explorer, you migk have totum script I debuwiW$qAs, Advance ta on t%e Internet Explorer Options dialog box Clicking the Yes button opens the Microsoft Script Debugger window, highlighting the source of the error As shown in Figure 10-32, the source of this particular error is that the showEM() function was referenced as showem() Because function names are case sensitive, the browser was unable to locate the function and reported an error You can learn more about the script debugger using the online help provided with the Microsoft Script Debugger or at the Microsoft Web site i Tutorial 10 Programming with JavaScript HTML and XHTML Microsoft Script Debugger window a 1; eH#c t ' - ~ c = " t e x t / jevescriPt.> stwvM ("rrldac" '%hag lpa") ; L \ B@ad of M u l t S c l v i c e M / a > ->555-3145.C/td> i! ,I' typc-l"rcrt/jaaserivtg> ~l~(=il~LIP".=vOg.l~"); i i/srzipo 1 t ~U>S55-4S€i*/ta> rcrS# rgargtu Firefox also provides the Firefox Error Console that displays all ofthe errors generated within the current document To view the list of errors, type javascript: in the address bar as shown in Figure 10-33 L L Figure 10-32 I II TML and XHTML Tutorial 10 Programming with JavaScript type javascript: into the addre bar to ooen the Error Console I ~ VS t a f f I D i r e c t o r y -.- Howard's e iddress is missing The Error Console appears as another Firefox browser window, as shown in Figure 10-34 Within the Error Console is an Evaluate box in which you can insert JavaScript commands to evaluate your code and variable values at the point at which the error occurred Figure 10-34 i entering JavaScript :ommands slIJcLky & L i . . .-&lick " ' to view the error I The Error Console also includes a hypertext link to another Firefox window that displays the code for the source file The point at which the error was first detected (not necessarily the source of the error) is highlighted in this window, as shown in Figure 10-35 - I Tutorial 10 Programming with ~ a v a ~ c rHTML i ~ i and XHTML / Hiehliehtine the source of the error I script typa-.tut/javnauipt9> ahOYe21(-reldaCw,~Vag.l~w): Firefox's Error Consde will also display syntax errors from your CSS style sheet or other warnings generated by mistakes in the HTML code I I b @ EXPLORE I where mapNum is the value of the mapNum variable Scroll down a few lines and replace the datehime value January1, 2011, 12:OO a.m with a script element that writes the value of the timeStr variable to the Web page Save your changes to the file and then open skymap.htm in your Web browser Verify that the planisphere displays the current date and time If you're able to modify the datdtime settings on your computer, change the date and time and then reload or refresh the page to verify that the datdtime value changes and that the map also changes Debug your code as necessary Submit your completed files to your instructor I Case Pro'blem2 Use lavascript to display random banner ads Data Files needed for this Case Problem: ad1.jpg through ad5.jpg, ads.js, fp.jpg, fronttxt.htm, logo.jpg, random.js, and styles.css Ridgewood Herald Tribune Maria Ramirez manages advertising accounts for the Ridgewood Herald Tribune in Ridgewood, New Jersey Recently, the paper has put more of its content online To offset the cost of the Web site, Maria is selling ad space on the company's home page She is looking at creating banner ads to be displayed on the paper's masthead, with each ad linked to the advertiser's Web site Because ad space on the paper's home page is the most valuable, Maria has decided to sell space to five companies, with the selection of the banner ad determined randomly each time a user opens the page 1Tutorial 10 Programming with JavaScript -ML and XHTMl r-i' ., - Maria has asked for your help in writing the JavaScript code to display banner ads ,.randomly She has provided a collection of functions that will be useful to you: -! The randlntO function, which returns random integers from tan-TQcall the randlnt.0 function, use the following expression: randInt (n) e , ; - , The adDescription0 function, which returns the description of the nth ad from a list of ad descriptions To call the function, use the following expression: adDescription(n1 The adlink() function, which returns the URL of the nth ad of the collection To call the function, use the following expression: adLink(n) ', *- ' The random.js file contains the randlntO function The ads.js file contains the adDesctiptionO and adLinkO functions Figure 10-38 shows a preview of the completed Web page with one of the random banner ads displayed at the top of the page a Figure 10-38 " , #" - today to pkc Park Opens Thc AdwnctPo Island mane parkopmdtsdoorrm Monday rms Ridgewood Th pak ollc dthe biggest in New Jawy, drew hrge now&, bot the bag lncs dm't dchr anyone.'I've baen watchngtbempuptheridcs nzrthclast year, it's reaiycx&ngto6dygetimidetbcgates!" raidRidgcwood I ' Complete the following: Use your text editor to open the fronttxt.htm file from the tutorial.1 O\case2 folder included with your Data Files Enter your name and the date in the comment section of the file Save the file as front.htm in the same folder After the link element in the head section, insert a script element accessing the functions in the random.js file Insert another script element accessing the functions in the ads.js file Scroll down the file to the div element with the id ads Replace the conteGt of the div element with a script element containing the following statements: a Declare a variable named rNumber equal to the value returned from the randlntO function using as the parameter value Append the following comment to the statement: generate a random integer from to b Declare a variable named rAd equal to the text string returned from the adDescription0 function using rNumber as the parameter value Append the following comment to the statement: description of the random ad c Declare a variable named rLink equal to the URL returned from the adLinkO function using rNumber as the parameter value Append the following comment: URL of the random ad d Insert a command to write the text to the Web document, where url is the value of the rLink variable, n is the value of the rNumber variable, and description is the value of the rAd variable 'iT' Save your changes to the file Open front.htm in your Web browser Refresh the Web.page multiple times, verifying that different banner ads appear each time the page is refreshed Debug your code as necessary Submit your completed files to your instructor Challenge I Explore how to write a script to display the daily calendar o f events at a student union I Case Problem Data Files needed for this Case Problem: back.jpg, friday.htm, functions.js, monday htm, mw.css, saturday.htm, schedule.css, sundayhtm, thursday.htm, todaytxt.htm, tuesday.htm, and wednesday.htm Sean Lee manages the Web site for the student union at MidWest University in Salina, Kansas The student union provides daily activities for the students on campus As Web site manager, part of Sean's job is to keep the Web site up to date on the latest activities sponsored by the union At the beginning of each week, she revises a set of seven Web pages detailing the events for each day in the upcoming week Midwest Student Union Sean would like the Web site to display the current day's schedule in an inline frame within the Web page named Today at the Union To this, her Web page must be able to determine the day of the week and then load the appropriate file into the frame She would also like the Today at the Union page to display the current day and date Figure 10-39 shows a preview of the page she wants you to create / Tutorial 10 Programming with lavascript HTML and XHTM I Thursday 1RW am to & * pm Exhibition: HighIightr from the YWU M Colketion Sean has created the layout of the page, and she needs you to write the scripts to insert the current date and the calendar of events for the current day To assist you, she has located two functions: The showDateO function, which returns a text string containing the current date in the format Weekday, Month Day, Year The function has no parameter values The weekDay0 function, which returns a text string containing the name of the current weekday, from Sunday through Saturday This function also has no parameter values !- ,' i., The two functions are stored in an external JavaScriptfile named functi0ns.j~.The daily schedules have been stored in files named sunday.htm through saturday.htm Complete the following: Use your text editor to open the todaytxt.htm file from the tutorial.1 O\case3 folder included with your Data Files Enter your name and the date in the comment section of the file and save it as today.htm In the head section just above the closing dhead> tag, insert a script element accessing the functi0ns.j~file Scroll down the file and locate the div element with the id dateBox Within this element insert a script element The script should run the following two commands: a Write the following HTML code to the Web page: ! i I + 74- '- Display the daily schedule in an inline frame Daily schedules are stored in the files sunday.htm through saturday-htm b Insert a command to write the HTML code ciframe sr~=~weekday.htm~>e/iframe> to the Web page, where weekday is the text string returned by the weekDayO function .,! , -7 -1 I I b Write the text string returned by the showDateO function to the Web document Scroll down the file and locate the h2 heading Today at the Union Within the empty paragraph that follows this heading, insert another script element Within the script element, the following: a Insert the following multiline comment: - 21 I' Today is cbr /> EXPLORE I I I 1 HTML and XHTML Tutorial 10 Programming with JavaScript Save your changes to the document Open today.htm in your Web browser Verify that it shows the current date and that the daily schedule matches the current weekday, If you have the ability to change your computer's date and time, change the date to different days of the week and refresh the Web page Verify that the date and the daily schedule change to match the new date you selected Debug your code as necessary Submit your completed files to your instructor @EXPLORE Create : : i I Test your knowledge of lavascript by creating a splash screen displaying famous birthdays Case Problem Data Files needed for this Case Problem: functionajs and Isgo.jpg HappyBirthdayNews.com Linda Chi is the owner of a Web site called HappyBirthdayNews.com that specializes in birthday gifts and memorabilia To make her site more interesting for users, Linda wants to create a splash screen that displays the current date and a famous birthday occurring on that date She has asked for your help in writing the JavaScriptcode to generate the welcome message She has designed the page's style and content, and has also located the following lavascript functions: The showDateO function, which returns the current date in the text string Weekday, - Month Day, Year, where Weekday is the day of the week, Month is the name of the month, Day is the day of the month, and Year is the four-digit year value The showDateO function has no parameters The dayNumberO function, which returns the day number of the current date, ranging from (the first day of the year) to 366 (the last day of the year) The dayNumberO function has no parameters The showBirthDayO function, which returns a text string describing a famous birthday on the given date The function has a single parameter day-which is equal to the day number of the famous birthday you want to view The three functions have already been saved for you in a file named functi0ns.j~ Figure 10-40 shows one possible solution to this problem Figure 10-40 A *>>+ - A , ITutorial 10 Pronramminnwith IavaScriot HTML and XHTML HTML 613 Complete the following: F Use your text editor to create the file birthday.htm and save i t in the ,- @EXPLORE tutorial.1 O\case4 folder included with your Data Files Create a comment section containing your name and the date as well as a brief description of the Web page Create a splash screen introducing the HappyBirthday.com Web site The content and design of the site are up to you You can use the logo.jpg graphic file as the logo for the Web site and supplement it with any other content or graphics you find Use your knowledge of JavaScript to add the following features to the Web page: A page element that displays the current date A page element that displays the name of a famous person born on that date Any comments that document each of the variables you use in writing your JavaScriptcode and any functions you create Save your changes to the file and then open it in your Web browser Verify that the page displays the current date'and a famous person's birthday for that date If you're able to change the date on your computer's clock, change the date and refresh the Web page Verify that the page displays the new date and a new famous birthday Debug your code as necessary Submit your completed files to your instructor Session 10.1 A client-side program i s a program that i s run on a user's computer, usually with a Web browser A server-side program runs off of a Web server document write (~~ch2>Public Library"); do~ument.write(~ch2id="subW>Public Libraryc/h2>'); Place the backslash (\) symbol at the end of the line to indicate that the statement continues on the next line JavaScript is case sensitive, so this statement should read: document write ( lVMonroe Public Library") ; cp>ci>JavaScript required Session 10.2 var weekday = "Friday1' ; To calculate the sum of numeric values or to combine text strings into a single text string numeric, text, Boolean, and null mg + fileName + ' I ' alt=' ' / > ' I ) ; document ~ r i t e ( ~ ~ c isrc='I1 To perform an action or to return a value function Calcvol (x, y, z ) { vo1 = x*y*z; return Vol; I Lw HTML 614 TotalVol = CalcVol(3, 10, 4); Scope indicates where you can reference a variable within the Web page Session 10.3 cscript src="library.jsN type=utext/javascript~> / / Library of JavaScript functions / * I I The 1ibrary.j~file contains a collection of JavaScript functions for use with the file index.htm */ Debugging is the process of searching code to locate a source of trouble alert (userName); load-time error, run-time error, and logical error a run-time error r l Review ads.js front.htm random.js style.css + graphic files mpl2.htm mplstyles.css random.js + 11 graphic files datetime.js skymap.htm skyweb.css + 26 graphic files back.jpg functi0ns.j~ sunday.htm - saturday.htm today.htm + style sheets birthday.htm functi0ns.j~ logo.jpg styles.css [...]... results in an error message Figure 10- 12 shows the error message generated by the Internet Explorer browser The browser does not recognize the word Document (as opposed to document) and so cannot process the command You'll examine how to handle this type of error later in this tutorial 4L HTML 575 I I HTML 576 HTML and XHTML Tutorial 10 Programming with JavaScript Figure 10- 12 ) An Internet Explorer error... changes t o the file and reload mpLhtm in your Web browser As shown ) 8 inSaveFigure 10- 25, the text characters of the e-mail addresses for staff members now appear i n the correct order ( Figure 10- 24 HTML 594 )TML 1 and XHTML Tutorial 10 Programming with JavaScript I LII Staff Director" 9vv You review your progress with Kate As she scans through the code in the HTML file, she's pleased to note that... difficult to read and to type without making a mistake A browser treats these consecutive commands as one long string of text to be written into the document L e which is identical to the document.write0 methoc except that it adds a line I ITML and XHTML Tutorial 10 Programming with JavaScript Reference Window I I Writing to the Web Page 7 To write text t o the Web page with JavaScript, use the method... can see examples of this in Figure 10- 10, where the newly entered statements are indented several spaces to make the commands stand out from the opening and closing tags However, unlike HTML, you must be careful about line breaks occurring within a statement A line break cannot be placed within the name of a JavaScript command or within a quoted text string without causing an error in the code... HTML file to display the following paragraph for browsers that don't support JavaScript? cp>JavaScript required I HTML 577 Insight I I HTML ~ ~ * T M L and XHTML Tutorial 10 Programming with JavaScript Session 10. 2 Working with Variables In the previous session you learned how to write page content to a Web page using the document.write0 method Because you used this method to specify a text... 1 Return to the mpl.htm file in your text editor ) 2 Replace the three document.write() commands in the script with the following code, as shown in Figure 10- 15: do~ument.write(~ea href='mailto: document.write (emlink); document.write ("e/asn9; + d i n k + "'sm); I I Tutorial 10 Programming with JavaScript HTML and XHTML HTML 583 Writing the value of the emlink variable to the Web page , - u c r i p... address with this function call 7 -, r < ' S $aP,W l -8 r '&ifl thk'~fi~&~~()~hnction:L Return to the mpl.htm file in your text editor, and scroll down the file to the script element containing the JavaScript code for Catherine Adler's e-mail address ) 2 Replace all of the commands within the script element with the following command, as shown in Figure 10- 17: sho~EM(~cadler~,~mpl.gov'); I ,torial 10 Programming. .. that value to the z variable As a result d these commands, a value of 48 is assigned to the z variable - ! Tutorial 10 Programming with JavaScript HTML and XHTML HTML 589 Fuwions that return a value can be placed within larger expressions For example, the following code calls the CalcAreaO function within an expression that multiplies the area value by 2: var z = CalcArea(x,y)*2; When this command is... named Vol that is equal to x*y*z 7 Write the JavaScriptstatement to call the CalcVolO function with values of x = 3, y = 10, and z = 4, storing the result of the function in a variable named TotalVol 8 What is variable scope? 7 Review / HTML 590 HTML a n d XHTML Tutorial 10 Programming w i t h lavascript L Session 10. 3 Accessing an External JavaScript File You rhaw your work an the suff (di to Ute 5hetshappy... document just as if the programmer had entered the code from the external file directly into the Web file See Figure 10- 20 I Tutorial 10 Programming with JavaScript HTML and XHTML Using an external script file c i t l e m m w public Libruy 1

Ngày đăng: 30/05/2016, 00:05

Xem thêm: Tutorial 10 programming with javascript(2)

TỪ KHÓA LIÊN QUAN