Variables and Conditions Let's see an example:
<script>
var x=window.confirm("Are you
sure you want to quit");
if (x)
window.alert("Thank you.");
else
window.alert("Good choice.");
</script>
There are several concepts that we should know. First of all, "var
x=" is a variable declaration. If you want to create a variable,
you must declare the variable using the var statement. x
will get the result, namely, "true" or "false". Then we use a condition
statement "if else" to give the script the ability to choose between
two paths, depending on this result (condition for the following
action). If the result is true (the user clicked "ok"), "Thank you"
is alerted. If the result is false (the user clicked "cancel"),
"Good choice" is alerted instead. So we can make more complex boxes
using "var", "if" and those basic methods.
<script>
var y=window.prompt("please enter your name")
window.alert(y)
</script>
Another example:
<html><head>
<script>
var x=confirm("Are you sure you want to quit?");
if (!x)
window.location="http://www.onlineschoolnet.com";
</script>
</head>
<body>
Welcome to my website!.
</body></html>
If click "cancel", it will take you to onlineschoolnet.com, and clicking ok will
continue with the loading of the current page "Welcome to my website!".
Note:if (!x)means: if click "cancel". In JavaScript, the
exclamation mark (!) means: "none".
|