|
Free Open Book
Sams Teach Yourself JavaScript in 24 Hours |
Testing Multiple Conditions with if and elseYou can now create an example script using if and else. In Hour 2, "Creating Simple Scripts," you created a script that displays the current date and time. This example will use conditions to display a greeting that depends on the time: "Good morning," "Good Afternoon," "Good Evening," or "Good Day". To accomplish this, you can use a combination of several if statements: if (hours < 10) document.write("Good morning.");
else if (hours >= 14 && hours <= 17) document.write("Good afternoon.");
else if (hours >= 17) document.write("Good evening.");
else document.write("Good day.");The first statement checks the hours variable for a value less than 10in other words, it checks whether the current time is before 10:00 a.m. If so, it displays the greeting "Good morning." The second statement checks whether the time is between 2:00 p.m. and 5:00 p.m. and, if so, displays "Good afternoon." This statement uses else if to indicate that this condition will only be tested if the previous one failedif it's morning, there's no need to check whether it's afternoon. Similarly, the third statement checks for times after 5:00 p.m. and displays "Good evening." The final statement uses a simple else, meaning it will be executed if none of the previous conditions matched. This covers the times between 10:00 a.m. and 2:00 p.m. (neglected by the other statements) and displays "Good day." The HTML FileTo try this example in a browser, you'll need an HTML file. We will keep the JavaScript code separate, so Listing 7.1 is the complete HTML file. Save it as timegreet.html but don't load it into the browser until you've prepared the JavaScript file in the next section. Listing 7.1. The HTML File for the Time and Greeting Example
The JavaScript FileListing 7.2 shows the complete JavaScript file for the time greeting example. This uses the built-in Date object functions to find the current date and store it in hours, mins, and secs variables. Next, document.write statements display the current time, and the if and else statements introduced earlier display an appropriate greeting. Listing 7.2. A Script to Display the Current Time and a Greeting
To try this example, save this file as timegreet.js (or download it from this book's website) and then load the timegreet.html file into your browser. Figure 7.1 shows the results of this script. Figure 7.1. The output of the time greeting example, as shown by Internet Explorer.
|
Main Menu |
| 500 Juegos Gratis | 500 Giochi Gratis | 500 Jeux Gratuits | 500 Jogos Gratis | 500 Kostenlose Spiele |