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

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

61 369 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

Cấu trúc

  • The Book of JavaScript, 2nd Edition

    • Chapter 3: Giving the Browsers What They Want

    • Chapter 4: Working with Rollovers

    • Chapter 5: Opening and Manipulating Windows

    • Chapter 6: Writing Your Own JavaScript Functions

Nội dung

GIVING THE BROWSERS WHAT THEY WANT Much to the dismay of web developers everywhere, different browsers implement JavaScript and HTML in slightly different ways Wouldn’t it be great if you could serve each browser exactly the content it could understand? Fortunately, you can use JavaScript to determine which browser a visitor is using You can then use that information to deliver content suitable for that specific browser, either by redirecting the visitor to a page containing content especially tailored for that browser or by writing your JavaScripts so that the same page does different things depending on the browser looking at it This chapter covers the three topics you need to understand to deliver browser-specific pages using redirects: How to determine which browser your visitor is using How to redirect the visitor to other pages automatically How to send the visitor to the page you want, depending on which browser he or she is using As in Chapter 2, while learning how to handle an important web authoring task, you’ll also be introduced to fundamental elements of the JavaScript language—in this case, if-then statements and related methods for implementing logical decision making in your scripts Let’s first talk about determining which browser a visitor is using A Real-World Example of Browser Detection Before we get into the details of how browser detection works, let’s look at a real-world example Netscape, the company that brought you the Netscape Navigator browser, has a complicated home page with lots of interesting features They’ve taken great pains to make their home page look good to most browsers, including early versions of their own browser If you compare the Netscape home page seen with Netscape Navigator (Figure 3-1) to the page seen using Navigator (Figure 3-2), you’ll notice some subtle differences Among other things, the news blurb at the bottom of Figure 3-2 has a little navigational element in the lower-right corner Clicking the numbers in that corner cycles you through different news blurbs Figure 3-1 does not have these numbers, probably because there isn’t a good way to provide this fancy functionality in the old Netscape Navigator Figure 3-1: Netscape Navigator view of Netscape home page Figure 3-2: Netscape Navigator view of Netscape home page How does Netscape show the numbers to only those browsers that can provide this feature? There are two steps First you have to determine which browser your visitor is using Once you know the browser, you know what JavaScript and HTML features it supports Then you have to figure out how to control what the person will see based on the known capabilities of the browser 34 Chapter Browser Detection Methods A browser is identified by its name (Netscape, Firefox, Internet Explorer, and so on) combined with its version number Your JavaScript needs to determine both of these items There are two ways to approach this task: a quick but rough method and a slightly less quick but more accurate method Quick-but-Rough Browser Detection In general, the line var browser_name = navigator.appName; determines who made the browser If the user is using a Netscape browser, the variable browser_name will be set to the string "Netscape" If it’s a Microsoft Internet Explorer browser, browser_name will be set to "Microsoft Internet Explorer" Every JavaScript-enabled browser must have the variable navigator.appName If you use Opera, navigator.appName equals "Opera" Unfortunately, some browsers travel incognito For example, the navigator.appName for Firefox is "Netscape" The JavaScript in Firefox is the same as that for Netscape browsers, so in general, it’s fine to treat Firefox browsers as Netscape browsers But, as you can see, if you want to be sure about the browser being used, you can’t rely on naviagor.appName There’s a similar rough method for determining the browser version being used: navigator.appVersion Unfortunately, navigator.appVersion isn’t just a number but a sometimes cryptic string that varies from browser to browser For example, the Macintosh browser Safari has this nice, simple navigator.appVersion string: "5.0" By contrast, Internet Explorer 6.0 running under Windows XP has a navigator.appVersion that looks like this: "4.0 (compatible; MSIE 6.0; Windows NT 5.1; NET CLR 1.1.4322)" To see the navigator.appVersion string for your browser, type this into the browser’s address box (where you normally enter web addresses): javascript:alert(navigator.appVersion) If you care only about whether a person is using a 4.0 browser or later, you can pick out the version numbers from those navigator.appVersion strings with the parseFloat() command, which looks at the string and grabs the first item that resembles a floating-point number (a number that contains a decimal point) Thus the line var browser_version = parseFloat(navigator.appVersion); sets the variable browser_version to the first number in the navigator.appVersion string For most browsers, this will be the actual version number For Internet Explorer, it will be 4.0 for any version of the browser 4.0 or later You can see why I call this method rough G i v i n g th e B ro w s e r s W h a t T h e y W an t 35 More Accurate Browser Detection JavaScript has another variable that contains information about the browser being used: navigator.userAgent This variable identifies both the manufacturer of the browser and its version As it did with navigator.appVersion, however, the formatting of the string varies from browser to browser Because the navigator.userAgent strings are different from each other, there is no simple way to extract the information you want Fortunately, people have already written browser sniffers: bits of JavaScript that will all the hard work of browser identification for you You can find brwsniff.js, which I downloaded from http://jsbrwsniff.sourceforge.net, at http:// www.bookofjavascript.com/Chapter03 To use this file, put it in the same folder as the web page containing your JavaScript Then, put this line in the header of your web page: This tells JavaScript to add the contents of the file named brwsniff.js to your web page Now you can use the JavaScript stored in that file To use the JavaScript in brwsniff.js to determine the name and version of the browser being used to view your web page, add these lines of JavaScript: var browser_info = getBrowser(); var browser_name = browserInfo[0]; var browser_version = browserInfo[1]; Line calls a function in brwsniff.js that reads the navigator.userAgent string and compares it to all the different browser version strings it knows Once it determines the name and version of the browser, the function loads this information into a variable called browser_info All the variables we’ve seen so far store one piece of information—a string or a number, for example This browser_info variable is an array, a type of variable designed to hold multiple items of related information You’ll learn how to work with arrays in Chapter For now it’s enough to know that an array is a variable that can store more than one piece of information Line puts the first bit of information stored in the array into a variable called browser_name Line puts the second piece of information stored in browser_info into a variable named browser_version Used together, these two variables tell you what kind of browser is viewing the web page Try the web page in Figure 3-3 on your own browser NOTE This tag does not require the to hide it from older browsers because there is no code between the opening and closing tags The quick but rough method of browser detection should work for most situations, especially when you don’t need to know exactly which browser is being used For the cases in which you need the exact name and version, you should use a browser sniffer like the one just described 36 Chapter I Know Which Browser You're Using! Figure 3-3: Finding the browser version number with a browser sniffer Redirecting Visitors to Other Pages Now that you understand browser detection, you can tailor your site to provide information specific to each browser There are two main ways to this First, you can use document.write(), which we saw in the last chapter, to display one message on your page if the site visitor is using Netscape Navigator 4, and a different message on the same page for Internet Explorer 6.0 Alternatively, you can redirect your visitors to separate pages specifically tailored to different browsers To redirect visitors to another page, you’d write something like this: window.location.href = "http://www.mywebsite.com/page_for_netscape4.html"; When JavaScript sees a line like this, it loads the page with the specified URL into the browser NOTE Are you wondering “What’s with all these periods in commands like window.location.href and navigator.appName?” Never fear I’ll address these when I discuss image swaps and dot notation in Chapter In general, it’s probably best to use document.write() instead of redirecting the user Because there are so many browsers, trying to maintain a different page for each one can quickly become burdensome However, if you just want to redirect someone with an older browser to a page that tells them to upgrade, redirection is probably the best way to go G i v i n g th e B ro w s e r s W h a t T h e y W an t 37 if-then Statements Now that you know which browser your visitor is using, you need to learn how to tell JavaScript to write different things depending on the browser being used—in other words, how to implement a logical test, choosing between different actions based on specific information Branching is a fundamental technique in any programming or scripting language Be sure to read this section if you’re not already familiar with the concept To alter your web pages based on the browser a visitor is using, you tell JavaScript something like, “If the visitor is using Internet Explorer, then write this IE-tailored content.” An if-then statement in JavaScript looks like this: if (navigator.appName == "Microsoft Internet Explorer") { // write IE-specific content document.write("Welcome, Internet Explorer user!"); } Here’s the basic structure of an if-then statement: if (some test) { statement_1; statement_2; statement_3; } NOTE JavaScript is unforgiving: if must be lowercase, and you must put parentheses around the test that follows it The test that appears between the parentheses must be either true or false If the variable navigator.appName equals "Microsoft Internet Explorer", the test between the parentheses is true, and the statements located between the curly brackets are executed If the variable doesn’t equal "Microsoft Internet Explorer", the test between the parentheses is false, and the statements between the curly brackets aren’t executed Boolean Expressions The test in the parentheses after if is a Boolean expression—an expression that’s either true or false In JavaScript, a Boolean expression is usually a statement about the values of one or more variables Table 3-1 lists some of the symbols you’ll be using to form Boolean expressions in JavaScript NOTE 38 Chapter Boolean expressions are named after George Boole (1815–1864), who invented a way to express logical statements in mathematical form Table 3-1: Symbols in Boolean Expressions Test Meaning Example (All of These Are True) < Less than < > Greater than > == The same as (equal) "happy" == "happy", == != Different from (not equal) "happy" != "crabby", != = Notice in Table 3-1 that you must use two equal signs when you want JavaScript to test for equality in an if-then statement Boolean expression In fact, accidentally using one equal sign instead of two in an if-then statement is probably the major cause of mind-blowing programming errors As you learned in Chapter 2, a single equal sign is used to assign a value to a variable So if you accidentally use only one equal sign, JavaScript thinks you mean to set the variable on the left of the equal sign to the value of whatever is on the right of the equal sign, and it will act as if the test result is always true Here’s an example of the trauma that this mistake can cause Say you want to write a JavaScript that puts Happy Birthday, Mom! on your web page when it’s your mother’s birthday If her birthday were August 6, you might write something like Figure 3-4 (which contains the dreaded error) If you try this script, you’ll see that it always prints Happy Birthday, Mom! to the web page, which is great for Mom, but probably not what you want Figure 3-4: Mom’s birthday greeting—broken version G i v i n g th e B ro w s e r s W h a t T h e y W an t 39 The script starts off correctly When JavaScript sees , it sets the variable month to whatever month it is If you’re running the script in March, it sets month to The problem arises in the next line, though: if (month = 7) Here JavaScript sees one equal sign and thinks you want to set the variable month to the value The script does what you’re telling it to do, and then acts as if your test is true Since the result is true, JavaScript moves to the curly brackets, where it finds , another if-then statement that incorrectly uses one equal sign instead of two This line sets the variable day to the value and again results in a true statement JavaScript then moves to the second set of curly brackets, where it sees that it’s supposed to write Happy Birthday, Mom!, which it does— every time someone visits the page (see Figure 3-5) Figure 3-5: Mom’s birthday greeting NOTE I remember the difference between one and two equal signs by thinking is the same as instead of equals when I’m doing an if-then test, and remembering that is the same as translates into two equal signs Nesting Figure 3-4 is the first example I’ve used of nesting—one if-then statement inside another Although it sometimes makes sense to nest your if-then statements, things get confusing if you start to get three or more levels deep (one if-then statement inside the curly brackets of another if-then statement, which itself is inside the curly brackets of a third if-then statement) Try to write your code so that it doesn’t need more than two levels of nesting If you find yourself with if-then statements more than two levels deep, it often means that you’re doing something complicated enough to justify writing a new function to handle some of the complexity (More on that in Chapter 6.) if-then-else Statements There are a couple of fancier versions of the if-then statement The first is the if-then-else statement: if (navigator.appName == "Microsoft Internet Explorer") { // write IE-specific content 40 Chapter document.write("Welcome, Internet Explorer user!"); } else { // write netscape specific content document.write("Welcome, Netscape user!"); } This reads nicely in English if you read else as otherwise: “If they’re using Internet Explorer, show them IE-specific content, otherwise send them Netscape-specific content.” if-then-else-if Statements The above code assumes that there are only two browser manufacturers in the world, when in fact there are a multitude We can solve this problem with an if-then-else-if statement that, if a visitor has a browser other than Netscape or Internet Explorer, displays content regarding unknown browsers if (navigator.appName == "Netscape") { // write netscape-specific content document.write("Welcome, Netscape user!"); } else if (navigator.appName == "Microsoft Internet Explorer") { // write IE-specific content document.write("Welcome, Internet Explorer user!"); } else { // write unknown browser content document.write("Welcome, user of a fancy unknown browser!"); } This code reads in English as: “If they’re using Netscape, send them Netscape-specific content; if they’re using Internet Explorer, send them IEspecific content Otherwise send them a message about having a mysterious browser.” When and Where to Place Curly Brackets Notice in the examples above that curly brackets (braces) mark the beginning and end of the body of an if-then statement, enclosing the part where you tell JavaScript what action(s) to take You’ll also notice that I place my beginning and ending curly brackets on their own lines, like this: if (something == something_else) { blah_blah_blah; } G i v i n g th e B ro w s e r s W h a t T h e y W an t 41 This is my style, one that I think makes it easier to align pairs of beginning and ending brackets Other people prefer this slightly more compact style: if (something == something_else) { blah_blah_blah; } It’s up to you to choose where you put the curly brackets Many studies have tried to figure out which formatting style is most readable or which avoids bugs When you get right down to it, just decide what you think looks good and go with that Sometimes curly brackets are not needed in an if-then statement, such as when the body of the statement has only one line For example, this is legal: if (something == something_else) alert("they're equal"); else alert("they're different!"); Since each of the “then” parts of the clause is only one line (the alert functions), the curly brackets around these statements are optional However, it’s always a good idea to include the braces anyway, because you might want to add a second line to that else clause If you add a second line to the else clause and forget to put the brackets around the two lines, your script won’t work With curly brackets, the previous example would look like this: if (something == something_else) { alert("they're equal"); } else { alert("they're different!"); } Or, if you prefer the more compact style: if (something == something_else) { alert("they're equal"); } else { alert("they're different!"); } OR and AND The if-then statements we’ve seen so far are pretty simple You might, however, want to add more conditions to an if-then statement (for example, “If Joe is in high school and is not doing his homework, then tell him to get to work”) To add more conditions to an if-then statement, use the OR and AND operators 42 Chapter // similar calculation as for the left position var top_point = parseInt(height/2) - parseInt(window_height / 2); // move the window // window.moveTo(left_point, top_point); // show me > Hi! Figure 5-10: Code for moving a window to the center of the screen Lines through resize the window to 200 by 200 pixels Once that’s done, the script uses window.screen.availHeight and window.screen.availWidth to figure out how high and wide the screen is After determining those values, the script does some calculations to figure out where the upper-left corner of the window should go Let’s look at the formula to calculate the left-hand position of the window: var left_point = parseInt(width / 2) - parseInt(window_width / 2); The first part of this formula determines the screen’s midpoint by dividing the width of the screen by two (we’ve defined the variable width in ) The parseInt() command ensures that the resulting number is an integer Knowing the screen’s midpoint isn’t enough to center the window, however, because window.moveTo() sets the left border of the window you’re moving If you move the left border of the window into the center of the screen, the window will be too far to the right To get the window to the center of the screen, we have to move it over to the left The second part of the formula, subtracting parseInt(window_width / 2), figures out how far to move the window to the left: half the window’s width (see Figure 5-11) If you place the left side of the window in the middle of the screen, the window won’t be centered You have to move it a bit to the left To center the window, move it ½ of its width to the left In other words, the left border is: ½ screen width – ½ window width screen screen window window ½ window width ½ screen width ½ screen width Figure 5-11: Calculating how to center a window O pe n i n g an d M an i pu lati n g W i n w s 79 Line performs a similar calculation to determine where to set the top of the window Once we’ve determined the window’s correct top and left position, we use the window.moveTo() command to move it ( ) NOTE In Internet Explorer, the moveTo() method works only when it is moving the window containing the JavaScript In other words, if you have opened a window named my_window, you can’t move that window using my_window.moveTo(100,100) You can still use window.moveTo(100,100) to move the window that contains the JavaScript calling the moveTo() method Summary In this chapter you’ve learned: How to open new windows with window.open() How to incorporate various standard browser elements in the new window using the feature parameter How to close the windows you’ve opened with window_name.close() How to move windows to the front of the screen with window.focus() How to send windows to the back of the screen with window.blur() How to change the message in the window’s status bar by setting window.status How a window you’ve opened can affect the previous window with window.opener How to resize windows with window.resizeTo() and window.resizeBy() How to move windows with window.moveTo() and window.moveBy() Congratulations! Now that you know how to swap images and mess with windows, you can handle about 75 percent of what most web professionals with JavaScript The next few chapters will cover some details of JavaScript as a programming language, and then we’ll be ready for the really fancy stuff Assignment We’ve learned how to change the contents of the status bar of a window we’ve opened using JavaScript: var my_window = window.open("http://www.nostarch.com","my_window"); my_window.status = "I'm in the new window's status bar!"; We can use a similar technique to swap an image in a window we’ve opened using JavaScript Remember, the code to swap an image looks like this, where the_image is the name of an image on the page: window.document.the_image.src = "new_image.gif" 80 Chapter To swap an image in another window, just replace window in the script with the name of the window containing the image Your homework assignment is to write a page (let’s call it the main page) that contains two links Write some JavaScript so that when the main page opens, it also opens a little window containing an image When clicked, the two links on the main page swap different images into the little window Figures 5-12 and 5-13 demonstrate what I mean Figure 5-12: After opening the main window Figure 5-13: After clicking the Really Happy link This assignment is a bit tricky, but give it your best shot before looking at the solution in Appendix A O pe n i n g an d M an i pu lati n g W i n w s 81 WRITING YOUR OWN JAVASCRIPT FUNCTIONS In this chapter we’re going to focus on a programming concept—writing your own functions Knowing how to write your own functions will improve almost any JavaScript you create In fact, you’ll see how custommade functions can enhance several of the JavaScript tricks you’ve already learned In this chapter, you’ll learn how to: Write your own functions Use homemade functions to improve your code Write functions you can cut and paste into whatever pages you want We’ll be using homemade functions in every chapter from now on, so pay extra-close attention to what’s going on in this chapter You’ll be glad you did Functions as Shortcuts Functions aren’t anything new You’ve already seen a number of functions that come built in to JavaScript The alert() function, for example, takes whatever text you put inside the parentheses and displays an alert box with that text In its simplest form, function is just a shorthand name for a series of JavaScript instructions When you call the alert() function, JavaScript understands it as a command to carry out some task, such as opening a window that has an OK button and a close button and putting some text in the window The functions you create act as shorthand as well Let’s say you want to write a link that opens a small window and then centers that window on the screen if the visitor is using Netscape 4.0 or above You could write a link resembling Figure 6-1 (most of the code in it is similar to Figure 5-10) Click me to open a small centered window Figure 6-1: A link that opens a small window and centers it in Netscape and above— this won’t work in Internet Explorer (see note at the end of Chapter 5) However, it is not a good idea to write a link in this way: There’s too much JavaScript embedded in the HTML This makes HTML hard to follow, even for people who know JavaScript Furthermore, if you want two or three links on your page, your HTML becomes even uglier and your page’s download time increases Even more problematic, if you want to change the code to affect window size or centering, you have to make the change everywhere you put the link The solution to these problems is to give all the JavaScript in Figure 6-1 a name and then simply call that name when you want to open and center a window That’s exactly what homemade functions are for: They allow you to call a set of JavaScript instructions (the function) just by using its name Basic Structure of JavaScript Functions Figure 6-2 shows you the skeleton of a homemade function 84 Chapter function functionName() { a line of JavaScript; another line of JavaScript; more lines of JavaScript; } Figure 6-2: The basic structure of a homemade function A function definition starts with the word function When JavaScript sees that word, it knows you’re about to define the subsequent bunch of JavaScript as a function Naming Your Functions Next comes the function’s name The rules for naming a function are similar to those for naming a variable The first character must be a letter; the rest of the characters can include letters, numbers, dashes, and underscores No other characters, including spaces, are allowed Like variables, function names are case sensitive, so JavaScript will consider a function called feedTheCat() to be different from a function called FeedTheCat() Make sure you don’t give a function and a variable the same name If you have a variable called my_cat and a function called my_cat, JavaScript will forget either what the function’s supposed to or what value you’ve stored in the my_cat variable Because of this weird behavior, and because function names are case sensitive, it makes sense to have a different convention for naming functions than for naming variables For variables I use lowercase letters with underscores, and for functions I use what’s called in-caps or camel-caps notation Names in this notation style consist of strings of words without spaces, in which every word except the first is initial-capitalized, as in openAndCenterTheWindow(), myCat(), and printDate() In-caps notation is a pretty common convention and should serve you well Parentheses and Curly Brackets A pair of parentheses follows the function’s name For now, you won’t be entering anything between them, but they’re still necessary After the parentheses you need a pair of curly brackets Between these brackets you’ll write the JavaScript that will run when the function is called An Example of a Simple Function Figure 6-3 shows you how the window-centering code in Figure 5-10 looks rewritten as a web page containing a function Notice that the link calling the function ( ) has the same form as a link that calls a built-in JavaScript function—the function name appears inside an onClick W r iting You r O wn Jav aScript Functions 85 Getting Centered 3) && (navigator.appName == "Netscape")) { var the_window = window.open('http://www.nostarch.com/', 'the_window','height=200,width=200'); var screen_height = window.screen.availHeight; var screen_width = window.screen.availWidth; var left_point = parseInt(screen_width / 2) - 100; var top_point = parseInt(screen_height / 2) - 100; the_window.moveTo(left_point, top_point); } } // show me > Click me to open a small centered window Figure 6-3: Opening and centering a window using a function Next, notice that I’ve put the JavaScript declaring the function in the head of the page You can declare functions in either the head or the body of an HTML page, but I like to declare my functions in the head because that way I don’t have to search for them all over the page Finally, it’s important to remember that the browser reads the page from the top down When it sees the word function, it remembers the function name and the lines of JavaScript you’ve associated with that name However, the JavaScript between the curly brackets doesn’t actually execute until the onClick in the link calls the function When we start putting more than one function on a web page, you’ll see why it’s important to keep this in mind Writing Flexible Functions The code in Figure 6-3 does a good job of opening and centering a window containing No Starch Press’s home page But what if you wanted another link to open and center a different window with a different URL in it— Webmonkey’s, for example? 86 Chapter One approach would be to write a second function that looks just like the first one, the only difference being that you’d replace the line var the_window = window.open('http://www.nostarch.com/','the_window','height=200,width=200'); with the line var the_window = window.open('http://www.webmonkey.com/','the_window','height=200,width=200'); This would work fine, but it’s not a good idea to have two functions that almost exactly the same thing First of all, it’s wasteful If you could write one function that worked regardless of the URL, you’d save both typing and download time Even more important, if you want to change how you’re doing the centering, you’ll have to change two functions instead of just one Using Parameters Luckily, there’s a way to make your function more flexible The trick is to add a parameter Remember, the alert() function takes one parameter—the words you want to appear in the alert box You can write the openAndCenterWindow() function to take a parameter, too In this case, the parameter would be the URL of the web page you want to appear in the window In general, a function’s parameter is whatever item of information the function needs in order to its job—text to be displayed, a URL to link to, or whatever Many functions use multiple parameters The code in Figure 6-4 shows how to add a parameter to your function and how to call the function with this parameter Getting Centered Functionally 3) && (navigator.appName == "Netscape")) { var the_window = window.open(the_url,'the_window','height=200,width=200'); var screen_height = window.screen.availHeight; var screen_width = window.screen.availWidth; var left_point = parseInt(screen_width / 2) - 100; var top_point = parseInt(screen_height / 2) - 100; the_window.moveTo(left_point, top_point); } } W r iting You r O wn Jav aScript Functions 87 // show me > Click me to put the Webmonkey home page in a small centered window

Click me to put the No Starch Press home page in a small centered window Figure 6-4: Opening and centering a window with a parameter Line-by-Line Analysis of Figure 6-4 The tag for Webmonkey, Click me to put the Webmonkey home page in a small centered window calls the function with the URL for Webmonkey in parentheses (see the result in Figure 6-5) Here Webmonkey’s URL goes into the function just as the words go into the alert() function, but instead of any random string, it’s a URL Figure 6-5: The Webmonkey site, opened and centered 88 Chapter Similarly, the tag Click me to put the No Starch Press home page in a small centered window calls the function with the URL for No Starch Press Now let’s look at the function itself Only two lines differ from those in Figure 6-3 The first line of the function now looks like this: function openAndCenterWindow(the_url) Notice that a word appears inside the parentheses now This term is a variable, storing whatever value you’ll use when you call the function So if the line openAndCenterWindow("happy happy!"); calls the function, the variable the_url holds the value "happy happy!" When we call the function in Figure 6-4 as follows, the variable the_url holds the value "http://www.nostarch.com/": Click me to put the No Starch Press home page in a small centered window The second line in the function that differs from Figure 6-3 is , which opens the window In Figure 6-3 we opened the window with a web page: var the_window = window.open('http://www.nostarch.com/', 'the_window', 'height=200,width=200'); In Figure 6-4 we open the window with the variable that was set when the function was called: var the_window = window.open(the_url, 'the_window', 'height=200,width=200'); JavaScript sees the variable the_url and knows it’s a variable because no quotes surround it If the function has 'http://www.nostarch.com/' inside the parentheses, like this openAndCenterWindow('http://www.nostarch.com/'); the variable the_url has the value http://www.nostarch.com/, so the window opens with the No Starch Press home page Figure 6-6 shows you graphically what’s going on here W r iting You r O wn Jav aScript Functions 89 Function Definition function openAndCenterWindow(the_url) { var the_window= window.open(the_url, ", 'height=200,width=200'); } Function Call openAndCenterWindow('http://www.nostarch.com/'); Figure 6-6: Passing parameters Using More Than One Parameter Sometimes you want to change more than one thing each time you call a function The built-in JavaScript function prompt(), for example, can change two sets of words: the words that appear above the text box and those that appear within it When we call prompt() as follows, we pass in two parameters, separated by a comma: var the_answer = prompt("What's your favorite color?","yellow?"); The method window.open(), discussed in the last chapter, provides an example of three parameters: the URL you want to open inside the window, the name of the window, and the window’s features The functions you write can also take more than one parameter Let’s say you want to write a function to display a web page in a square window You might write a function that finds the name of the page and the length of one of the sides of a window Figure 6-7 shows you what this would look like Square Windows Open the Webmonkey home page in a big square window 90 Chapter Open the No Starch Press home page in a small square window Figure 6-7: Writing functions that take more than one parameter Notice that in two variables now appear between the parentheses following the function name: the_url and the_length In we’re calling the function as we would call prompt(), with two parameters separated by a comma Calling the function sets the first variable in the function definition to the first parameter, so in the case of , the_url is set to http://www.webmonkey.com/ Similarly, the second variable in the function definition is set to the second parameter in the function call If we call the function as in , the_length is set to 400 Figure 6-8 depicts the results of calling functions with two parameters Function Definition function openSquareWindow(the_url, the_length) { var the_features = "width=" + the_length + ",height=" + the_length, var the_window = window.open(the_url, "", the_features); } Function Call openSquareWindow('http://www.webmonkey.com/', 400); Figure 6-8: Calling functions with two parameters Getting Information from Functions You can also write functions that give information back to you Consider the prompt() function: var the_answer = prompt("What's your name?","Ishmael"); When a user types his or her name into the prompt box and clicks OK, the name goes into the variable the_answer In programming parlance, you’d say that the function prompt() returns the words typed into the prompt box The functions you write can return values as well Figure 6-9 shows a very simple example of how to make a function return values Date Printer Hello! Today is Figure 6-9: A script with a simple function that returns a value Line-by-Line Analysis of Figure 6-9 Most of the function should be familiar by now The first four lines create a new Date object and carry out a few method calls to get information from that object Line takes the information gathered and creates a nicely formatted date Notice that the line is var the_nice_date = the_month + "/" + the_day + "/" + the_year; and not var the_nice_date = "the_month/the_day/the_year"; The latter won’t work, because JavaScript won’t recognize the_month, the_day, or the_year as variables if they appear inside quotes The correct version of this line takes the variables out of the quotes and puts them together with slashes using the plus (+) sign In the incorrect version, the quotation marks stop JavaScript from interpreting the names as variables, so the web page would display Hello! Today is the_month/the_day/ the_year Line tells JavaScript to exit the function and return the value of the_nice_date to whatever variable is waiting for it In this case, the variable is today in Whenever JavaScript sees the word return in a function, it exits the function and outputs whatever value comes after return 92 Chapter Line calls the function getNiceDate(), which returns a nicely formatted date The code document.write(today) then puts the date on the web page, as shown in Figure 6-10 Figure 6-10: Returning the date Dealing with Y2K Figure 6-9 works fine, but it has a little problem Remember our discussion of the Y2K problem in the getYear() method of the Date object (“Writing the Date to Your Web Page” on page 26)? Different browsers deal with years differently In some versions of Netscape, getYear() returns the year minus 1900 So if it’s the year 2010, getYear() returns 110 Other versions return the full four-digit year if the year is before 1900 or after 1999 Different versions of Internet Explorer give different results for the same date as well The way to deal with this problem is to see whether the year returned by getYear()is less than 1000 If so, your visitor is using a browser that subtracts 1900 from the date if it’s after 1899 In this case, you can get the correct fourdigit year by adding 1900 to the date You’ll find a concise form for all this convoluted logic in the JavaScript function Y2K(), shown in Figure 6-11 function Y2K(the_date) { if (the_date < 1000) { the_date = the_date + 1900; } return the_date; } Figure 6-11: Dealing with the Y2K problem This function adds 1900 to the year if it is less than 1000 You can drop the Y2K() function into the script shown in Figure 6-8 to deal with its Y2K problem Figure 6-12 demonstrates how the two look together Date Printer

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

TỪ KHÓA LIÊN QUAN