Using Multi-level ConditionalsThere are times when you need more than two choices in a conditional test; then and else sometimes just aren't enough. While you can have nested levels of if, it's often simpler to just use a switch/case statement instead. The switch/case construct allows you to check a variable against multiple values. As you can see in Figure 3.7, this script returns one of three different Presidential quotes as alert dialogs, depending on which button the user clicks. Script 3.11 shows the HTML, which is fairly simple. Script 3.12, the JavaScript, uses the switch/case construct to differentiate between presidents. Figure 3.7. Calling the function with each of the three buttons in the top window results in three different responses, as shown in the three dialog boxes.Script 3.11. The HTML sets up the page for multi-level conditionals.
Script 3.12. This type of conditional allows you to check against multiple possibilities.
To use a switch/case statement: Tip
|